Here is 5 best methods to prevent access to your php file directly 

In this tutorial i will create 2 files , index.php and main.php . 

users will grant access to index.php file and we will prevent them from accessing other php files on the same folder

First lets set our index.php file code as shown in this picture

"data here " is your running code which users will get when they open your site , note that the code is excuted from main.php file .

index.php file code source : 
<?php
 
include 'main.php';
 
?>
the index.php file is including main.php , when users open your website the index.php code and main.php
code will run . 

here is best methods to prevent users from accessing main.php file . 

METHOD 1 

The file being accessed is always an included file

so we can use " get_included_files() " as the picture shows here 

the above picture shows the result when the user open main.php file directly : http://severpath/main.php,

he will get error message saying "Contact This email address is being protected from spambots. You need JavaScript enabled to view it."  if there is no included files "==1"

the main.php file source is : 
<?php

if(count(get_included_files()) ==1) exit("Error , Contact This email address is being protected from spambots. You need JavaScript enabled to view it.");

echo "data here" ;

?>

METHOD 2

Using debug_backtrace() , 

main.php source file : 
<?php

debug_backtrace() || die ("Direct access not permitted");

echo "data here" ;

?>

METHOD 3

Using eregi Case insensitive regular expression match

change "main.php" to your php file . 

main.php source file : 
<?php

if (eregi("main.php", $_SERVER['PHP_SELF'])) { 
 die("<h4>You don't have right permission to access this file directly.</h4>");
}

echo "data here" ;

?>

METHOD 4

Using strpos Find the position of the first occurrence of a substring in a string

main.php source file : 
<?php

if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false)
{die('Error , Contact This email address is being protected from spambots. You need JavaScript enabled to view it.');}

echo "data here" ;
?>

METHOD 5

Using basename to check $_SERVER['PHP_SELF']. 
main.php source file : 
<?php

if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) 
{ die('Error , Contact This email address is being protected from spambots. You need JavaScript enabled to view it.'); };

echo "data here" ;
?>

Better Solution

The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request..

Alternative way 

An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file
<FilesMatch "\.(inc)$">
 
Order deny,allow
Deny from all

<FilesMatch>