Search the blog

To prevent direct access to a PHP page you should ideally place it outside of the web root. However, if this isn’t practical you can use this function.

if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) {

    header('HTTP/1.0 404 Not Found');

    // Handle your error here

    exit;

}

__FILE__ always returns the path to the current script — even if it’s an include — whereas $_SERVER['SCRIPT_FILENAME'] returns the top-level script that was called. If you want to use this script as a function you must pass __FILE__ to the function, rather than use it inside the function, else __FILE__ will always hold the value of the file that contains the function.

Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.