Tuesday, April 23, 2013

PHP Redirect from a single page to the home page.

When we develop websites using PHP, we normally develop pages that are included in other pages.  For example, the header.php or footer.php pages are included on the top and bottom of every page respectively, to avoid rewriting of these pages numerous times.  However, a smart cookie could figure out these pages and go directly to them by typing their url in the browser window.  A professional developer would take precautions to avoid this contingency and redirect any anonymous user visitor to the appropriate page.  For example, if someone types www.yourdomain.com/header.php or www.yourdomain.com/footer.php etc.  they should be redirected to the home page.  PHP has no direct function to accomplish this task.  However, the solution to accomplish this would be typing the following code at the top of the page:


$filename = __FILE__;
if(preg_match("/header.php/",$filename)){
header("Location:/");
die();
}

The first line of the code uses a PHP Defined Constant to obtain the name of the file and store it in a variable called filename.  The second line of the the code uses an if statement and Regular Expressions to check if the url contains header.php, and redirects the user to the home page.  Regular expressions are being widely used in Object Oriented Programming and Database Administration to perform advanced searches.  ABCO Technology provides comprehensive training in it's PHP Module located within the CIW Program. Contact us at (310) 216-3067 to obtain enrollment information in our upcoming CIW Classes.  For more information about the program, visit our website at www.abcotechnology.com