how to load DB login info from external file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

how to load DB login info from external file?

Post by someguyhere »

At the top of several pages, I have the following code to connect to a DB:

Code: Select all

$mysqli = new mysqli("localhost", "db_user", "db_password", "db_name");
I'd like to externalize it using require_once or something like that, so that I only have to maintain one file (it will have other configuration settings as well). When I tried require_once, it just displayed the single line from the file and then died.

What is the right/best approach?

file_get_contents()
require_once()
include_once()

Something else?
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: how to load DB login info from external file?

Post by califdon »

The normal practice is to use require_once(). Be sure that the other file has <?php and ?> tags in it. If you do that and it fails, something else is wrong with your script.
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: how to load DB login info from external file?

Post by someguyhere »

califdon wrote:Be sure that the other file has <?php and ?> tags in it.
That's what I did wrong. I assumed since it was being pulled into a file that already had the opening and closing php tags, it wasn't needed. Bad assumption :)
Post Reply