O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required