Databases Reference
In-Depth Information
for a particular file; the file will only be read in once. Here's how you'd rewrite the
previous examples with require_once( ) . First, there's musicheader.php :
<?php
require_once "db.php";
function musicconnect()
{
// Connect to the MySQL server
if (!($connection = @ mysql_connect($host, $username, $password)))
die("Cannot connect");
if (!(mysql_select_db($database, $connection)))
showerror($connection);
return $connection;
}
?>
Second, there's the script:
<?php
require_once "db.php";
require_once "musicheader.php";
$conn = musicconnect();
...
?>
The script now works as desired. We use require_once( ) in preference to require( )
because it automatically looks after the problem we've shown, and we recommend you
do the same.
There are rare cases where you do actually want a header file to be included and pro-
cessed multiple times; for example, you could have a set of statements that are loaded
and run in the body of a loop, as in:
for($i=0; $i<10; $i++)
{
// Load the header file
require("myfile.php");
}
However, this code isn't efficient (a custom function would be faster), so you're gen-
erally better off avoiding require( ) .
Protecting Script and Header Files
Web database applications need to store the database user credentials in the PHP pro-
gram code. Users with accounts on your web server can access script and header files
directly from disk, so you should set the file permissions such that only the web server
 
Search WWH ::




Custom Search