PHP Page – Deny Public Access to it

This article is very informative if you start from .

With the below code, you are not actually denying access to your page but stopping unwanted code execution of the script.

Suppose PHP web page name is conn.php-

Page:: conn.php

<?php
$conn = mysql_connect('127.0.0.1', 'userName', 'password');
if ($conn) {
 //echo 'conn successfull.';
}
else {
 //echo 'conn failed.';
 //echo mysql_error();
}
?>
Now the above code is important for database connection and you want to avoid access through url.
Add this code at the top of the page:

<?php
if (basename($_SERVER['PHP_SELF']) == 'conn.php') {
 die('You cannot load this page directly.');
}
?>
By writing your code at top of the PHP web page you can be sure that your important code is safe. This code will also save and stop errors that can come after loading if the file cannot run without its helper page or variables from other page.
If you want to really deny access to any page or group of pages with common file extension, then deny it from Apache configuration file.