Include Files

Example 11-3 shows the db.inc file that is included in each of the gift registry scripts. The include directive allows the variables and functions in db.inc to be used by each script without duplicating the code. Note that the code in include files must always be surrounded by PHP start and end tags.

Example 11-3. The db.inc include file
<?php
  
// These are the DBMS credentials and the database name
$hostName = "localhost";
$databaseName = "wedding";
$username = "fred";
$password = "shhh";
  
// Show an error and stop the script
function showerror(  )
{
   if (mysql_error(  ))
      die("Error " . mysql_errno() . " : " . mysql_error(  ));
   else
      die("Could not connect to the DBMS");
}
  
// Secure the user data by escaping characters and shortening the input string
function clean($input, $maxlength)
{
  $input = substr($input, 0, $maxlength);
  $input = EscapeShellCmd($input);
  return ($input);
}
  
// Check if the user is logged in. If not, send him to the login page
function logincheck(  )
{
   session_start(  );
  
   if (!session_is_registered("user"))
      // redirect to the login page
      header("Location: index.php");
}
?>

The db.inc include file stores the four variables that are used in connecting to the DBMS and selecting the database. The showerror( ) function is discussed in the previous section. The clean( ) function is discussed below. The logincheck( ) function is discussed in Section 11.5.

The include file has an .inc extension, which presents a minor security problem. If the user creates a URL to request the include file, the source of the include file will be shown in the browser. The user can then see the DBMS credentials and some of the source code. These details should be secure.

You can secure your .inc files by configuring the web server so that retrieval of files with that extension is forbidden. With Apache, you can do this by adding the following to the httpd.conf file and restarting the web server:

<Files ~ ".inc$">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

Other approaches that achieve the same result are renaming the include file with a .php extension—so that the source is no longer output—or moving the include files outside of the web server’s document tree.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset