1.3. Writing Shared Code

Code that is shared by multiple files should be set aside in its own file and included using include or require so it's not duplicated, which makes maintaining the application easier. Where possible, code that might be useful in future applications should be collected separately as functions or classes to be reused. It's a good idea to write code with reusability in mind. common.php contains shared code to be included in other scripts in the application to establish a sane baseline environment at runtime. Since it should never be called directly by a user, it should be saved in the lib directory.

<?php
// set true if production environment else false for development
define ('IS_ENV_PRODUCTION', true);

// configure error reporting options
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', !IS_ENV_PRODUCTION);
ini_set('error_log', 'log/phperror.txt'),

// set time zone to use date/time functions without warnings
date_default_timezone_set('America/New_York'),

// compensate for magic quotes if necessary
if (get_magic_quotes_gpc())
{
    function _stripslashes_rcurs($variable, $top = true)
    {
        $clean_data = array();
        foreach ($variable as $key => $value)
        {
            $key = ($top) ? $key : stripslashes($key);
            $clean_data[$key] = (is_array($value)) ?
                stripslashes_rcurs($value, false) : stripslashes($value);
        }
        return $clean_data;
    }
    $_GET = _stripslashes_rcurs($_GET);
    $_POST = _stripslashes_rcurs($_POST);
    // $_REQUEST = _stripslashes_rcurs($_REQUEST);
    // $_COOKIE = _stripslashes_rcurs($_COOKIE);
}
?>

You may not always have control over the configuration of your server so it is wise to specify some common directives to make your applications more portable. Setting error reporting options, for example, lets you display errors while in development or redirect them in a production environment so they don't show to the user.

Magic quotes is a configuration option where PHP can automatically escape single quotes, double quotes, and backslashes in incoming data. Although this might seem useful, assuming whether this directive is on or not can lead to problems. It's better to normalize the data first and then escape it with addslashes() or mysql_real_escape_string() (preferably the latter if it's going to be stored in the database) when necessary. Compensating for magic quotes ensures data is properly escaped how you want and when you want despite how PHP is configured, making development easier and less error-prone.

Establishing a connection to a MySQL database is a common activity which makes sense to move out to its own file. db.php holds configuration constants and code to establish the connection. Again, as it is meant to be included in other files and not called directly, it should be saved in lib.

<?php
// database connection and schema constants
define('DB_HOST', 'localhost'),
define('DB_USER', 'username'),
define('DB_PASSWORD', 'password'),
define('DB_SCHEMA', 'WROX_DATABASE'),
define('DB_TBL_PREFIX', 'WROX_'),

// establish a connection to the database server
if (!$GLOBALS['DB'] = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD))
{
    die('Error: Unable to connect to database server.'),
}
if (!mysql_select_db(DB_SCHEMA, $GLOBALS['DB']))
{
    mysql_close($GLOBALS['DB']);
    die('Error: Unable to select database schema.'),
}
?>

The DB_HOST, DB_USER, DB_PASSWORD and DB_SCHEMA constants represent the values needed to establish a successful connection to the database. If the code is put into production in an environment where the database server is not running on the same host as PHP and the web server, you might also want to provide a DB_PORT value and adjust the call to mysql_connect() appropriately.

The connection handle for the database is then stored in the $GLOBALS super global array so it is available in any scope of any file that includes db.php (or that is included in the file that has referenced db.php).

Prefixing table names helps prevent clashes with other programs' tables that might be stored in the same schema and providing the prefix as a constant makes the code easier to update later if it should change, since the value appears just in one place.

Common functions can also be placed in their own files. I plan to use this random_text() function, for example, to generate a CAPTCHA string and validation token so it can be saved in a file named functions.php.

<?php
// return a string of random text of a desired length
function random_text($count, $rm_similar = false)
{
    // create list of characters
    $chars = array_flip(array_merge(range(0, 9), range('A', 'Z')));

// remove similar looking characters that might cause confusion
    if ($rm_similar)
    {
        unset($chars[0], $chars[1], $chars[2], $chars[5], $chars[8],
            $chars['B'], $chars['I'], $chars['O'], $chars['Q'],
            $chars['S'], $chars['U'], $chars['V'], $chars['Z']);
    }

    // generate the string of random text
    for ($i = 0, $text = ''; $i < $count; $i++)
    {
        $text .= array_rand($chars);
    }

    return $text;
}
?>

An important rule when programming no matter what language you're using is to never trust user input. People can (and will) provide all sorts of crazy and unexpected input. Sometimes this is accidental, at other times it's malicious. PHP's filter_input() and filter_var() functions can be used to scrub incoming data, though some people still prefer to write their own routines, as the filter extension may not be available in versions prior to 5.2.0. If you're one of those people, then they can be placed in functions.php as well.

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

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