Prevent direct access to a php include file












150















I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.



Basically I need to do a check as follows in the php file:



if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");


Is there an easy way to do this?










share|improve this question




















  • 9





    instead of the die() you should test 'header("HTTP/1.1 404 File Not Found", 404); exit;'. This will (at least on apache) make the server return the normal 404 page.

    – gnud
    Jan 4 '09 at 17:08











  • Here are two easy methods I have explain to disable direct access in PHP included files - codespeedy.com/disable-direct-access-to-the-php-include-file

    – Faruque Ahamed Mollick
    Jul 18 '17 at 21:06
















150















I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.



Basically I need to do a check as follows in the php file:



if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");


Is there an easy way to do this?










share|improve this question




















  • 9





    instead of the die() you should test 'header("HTTP/1.1 404 File Not Found", 404); exit;'. This will (at least on apache) make the server return the normal 404 page.

    – gnud
    Jan 4 '09 at 17:08











  • Here are two easy methods I have explain to disable direct access in PHP included files - codespeedy.com/disable-direct-access-to-the-php-include-file

    – Faruque Ahamed Mollick
    Jul 18 '17 at 21:06














150












150








150


84






I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.



Basically I need to do a check as follows in the php file:



if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");


Is there an easy way to do this?










share|improve this question
















I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.



Basically I need to do a check as follows in the php file:



if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");


Is there an easy way to do this?







php include include-guards






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 6 '13 at 14:10









Antony

13.1k103768




13.1k103768










asked Jan 3 '09 at 18:07









AlterlifeAlterlife

3,85862544




3,85862544








  • 9





    instead of the die() you should test 'header("HTTP/1.1 404 File Not Found", 404); exit;'. This will (at least on apache) make the server return the normal 404 page.

    – gnud
    Jan 4 '09 at 17:08











  • Here are two easy methods I have explain to disable direct access in PHP included files - codespeedy.com/disable-direct-access-to-the-php-include-file

    – Faruque Ahamed Mollick
    Jul 18 '17 at 21:06














  • 9





    instead of the die() you should test 'header("HTTP/1.1 404 File Not Found", 404); exit;'. This will (at least on apache) make the server return the normal 404 page.

    – gnud
    Jan 4 '09 at 17:08











  • Here are two easy methods I have explain to disable direct access in PHP included files - codespeedy.com/disable-direct-access-to-the-php-include-file

    – Faruque Ahamed Mollick
    Jul 18 '17 at 21:06








9




9





instead of the die() you should test 'header("HTTP/1.1 404 File Not Found", 404); exit;'. This will (at least on apache) make the server return the normal 404 page.

– gnud
Jan 4 '09 at 17:08





instead of the die() you should test 'header("HTTP/1.1 404 File Not Found", 404); exit;'. This will (at least on apache) make the server return the normal 404 page.

– gnud
Jan 4 '09 at 17:08













Here are two easy methods I have explain to disable direct access in PHP included files - codespeedy.com/disable-direct-access-to-the-php-include-file

– Faruque Ahamed Mollick
Jul 18 '17 at 21:06





Here are two easy methods I have explain to disable direct access in PHP included files - codespeedy.com/disable-direct-access-to-the-php-include-file

– Faruque Ahamed Mollick
Jul 18 '17 at 21:06












34 Answers
34






active

oldest

votes













1 2
next












153














The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:



Deny from all


If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.






share|improve this answer





















  • 1





    Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

    – Alterlife
    Jan 3 '09 at 18:23






  • 22





    if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

    – Eineki
    Jan 3 '09 at 19:43






  • 20





    It'd be nice to have an example .htaccess file as part of this answer.

    – Graham Lea
    Jun 5 '12 at 11:47






  • 7





    <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

    – Dracorat
    Sep 27 '12 at 16:53






  • 9





    @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

    – Chuck
    Sep 10 '13 at 21:03





















171














Add this to the page that you want to only be included



<?php
if(!defined('MyConst')) {
die('Direct access not permitted');
}
?>


then on the pages that include it add



<?php
define('MyConst', TRUE);
?>





share|improve this answer





















  • 3





    I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

    – Mark Davidson
    Jan 3 '09 at 18:17






  • 3





    This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

    – UnkwnTech
    Jan 3 '09 at 18:20






  • 1





    Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

    – bandi
    Jan 4 '09 at 10:05






  • 6





    Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

    – gnud
    Jan 4 '09 at 13:24






  • 3





    @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

    – James
    Sep 10 '13 at 16:43





















104














I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print() vs return()) Here's some modified code:



if(count(get_included_files()) ==1) exit("Direct access not permitted.");


The file being accessed is always an included file, hence the == 1.  






share|improve this answer





















  • 10





    That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

    – Akoi Meexx
    Jun 8 '11 at 16:40











  • First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

    – Jimbo Jonny
    Aug 8 '12 at 12:34











  • This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

    – Anuj
    Sep 18 '12 at 20:55






  • 3





    This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

    – jmucchiello
    Jun 10 '13 at 1:26











  • This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

    – whiteatom
    Jul 12 '13 at 16:19



















31














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.



I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.






share|improve this answer



















  • 2





    This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

    – Beau Simensen
    Jan 3 '09 at 19:29






  • 2





    In every hosting provider I worked with I always had access to (exactly) one level above the document root.

    – Eran Galperin
    Jan 3 '09 at 21:21






  • 3





    At some hosts (including my current one), you can point your domain to whichever folder you wish.

    – Dinah
    Jun 23 '09 at 15:43






  • 1





    This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

    – MarcoZen
    Nov 30 '17 at 15:13











  • That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

    – Funk Forty Niner
    May 8 '18 at 13:22





















25














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>





share|improve this answer





















  • 2





    +1 for syntax hints for us lazy types!

    – Kyle
    Oct 17 '11 at 18:23



















22














1: Checking the count of included files



if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
{
exit('Restricted Access');
}


Logic: PHP exits if the minimum include count isn't met. Note that prior to PHP5, the base page is not considered an include.





2: Defining and verifying a global constant



// In the base page (directly accessed):
define('_DEFVAR', 1);

// In the include files (where direct access isn't permitted):
defined('_DEFVAR') or exit('Restricted Access');


Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.





3: Remote address authorisation



// Call the include from the base page(directly accessed):
$includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

// In the include files (where direct access isn't permitted):
$src = $_SERVER['REMOTE_ADDR']; // Get the source address
$auth = authoriseIP($src); // Authorisation algorithm
if( !$auth ) exit('Restricted Access');


The drawback with this method is isolated execution, unless a session-token provided with the internal request. Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.





4: Token authorisation



Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:



if($key!="serv97602"){header("Location: ".$dart);exit();}


A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.





5: Webserver specific configuration



Most servers allow you to assign permissions for individual files or directories. You could place all your includes in such restricted directories, and have the server configured to deny them.



For example in APACHE, the configuration is stored in the .htaccess file. Tutorial here.



Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers. In such cases where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome. In the end it's best to handle this in code.





6: Placing includes in a secure directory OUTSIDE the site root



Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.



//Your secure dir path based on server file-system
$secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
include($secure_dir."securepage.php");


Logic:




  • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.

  • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can.

  • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.

  • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.




Please excuse my unorthodox coding conventions. Any feedback is appreciated.






share|improve this answer


























  • i like the number 2

    – Baim Wrong
    Apr 18 '18 at 14:53



















14














Actually my advice is to do all of these best practices.




  • Put the documents outside the webroot OR in a directory denied access by the webserver
    AND

  • Use a define in your visible documents that the hidden documents check for:


      if (!defined(INCL_FILE_FOO)) {
header('HTTP/1.0 403 Forbidden');
exit;
}


This way if the files become misplaced somehow (an errant ftp operation) they are still protected.






share|improve this answer

































    7














    I had this problem once, solved with:



    if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...


    but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.






    share|improve this answer































      5














      You'd better build application with one entrance point, i.e. all files should be reached from index.php



      Place this in index.php



      define(A,true);


      This check should run in each linked file (via require or include)



      defined('A') or die(header('HTTP/1.0 403 Forbidden'));





      share|improve this answer































        4














        The easiest way is to set some variable in the file that calls include, such as



        $including = true;


        Then in the file that's being included, check for the variable



        if (!$including) exit("direct access not permitted");





        share|improve this answer



















        • 2





          This is dangerous if register_globals is on.

          – jmucchiello
          Jan 3 '09 at 18:51






        • 24





          PHP is dangerous if register_globals is on.

          – David Precious
          Jan 3 '09 at 18:56











        • @bigpresh super dangerous to be clear.

          – UnkwnTech
          Jan 4 '09 at 20:55



















        4














        What Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files.



        defined('_JEXEC') or die('Restricted access');


        or else



        one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.



        or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.






        share|improve this answer

































          4














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





          share|improve this answer

































            4














            I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest). Here is what worked for me.



            if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
            if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
            header("Location: /403");
            exit;
            }
            }





            share|improve this answer

































              3














              Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails. They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/. Something like this (not ideal, but you get the idea):



              app/
              |
              +--pub/
              |
              +--lib/
              |
              +--conf/
              |
              +--models/
              |
              +--views/
              |
              +--controllers/


              You set up your web server to use pub/ as document root. This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet. Another benefit besides security is that everything is in one place.



              This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.






              share|improve this answer
























              • After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                – user4108694
                Feb 15 '16 at 11:45





















              2














              If more precisely, you should use this condition:



              if (array_search(__FILE__, get_included_files()) === 0) {
              echo 'direct access';
              }
              else {
              echo 'included';
              }


              get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array).
              So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.






              share|improve this answer































                1














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


                place the code above in the top of your included php file.



                ex:



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

                // do something
                ?>





                share|improve this answer
























                • eregi is deprecated now. Replace with preg_match as shown below...

                  – MarcoZen
                  Nov 30 '17 at 15:11













                • if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                  – MarcoZen
                  Nov 30 '17 at 15:12



















                1














                The following code is used in the Flatnux CMS (http://flatnux.altervista.org):



                if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
                {
                header("Location: ../../index.php");
                die("...");
                }





                share|improve this answer































                  1














                  if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };





                  share|improve this answer































                    1














                    My answer is somewhat different in approach but includes many of the answers provided here. I would recommend a multipronged approach:




                    1. .htaccess and Apache restrictions for sure

                    2. defined('_SOMECONSTANT') or die('Hackers! Be gone!');


                    HOWEVER the defined or die approach has a number of failings. Firstly, it is a real pain in the assumptions to test and debug with. Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind. "Find and replace!" you say. Yes, but how sure are you that it is written exactly the same everywhere, hmmm? Now multiply that with thousands of files... o.O



                    And then there's .htaccess. What happens if your code is distributed onto sites where the administrator is not so scrupulous? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.



                    So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".



                    What I suggest is:




                    1. Before any of your scripts require('ifyoulieyougonnadie.php'); (not include() and as a replacement for defined or die)


                    2. In ifyoulieyougonnadie.php, do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403, etc.



                      I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things. If the request to ifyoulieyougonnadie.php doesn't come from one of those two files, I know shenanigans are being undertaken!



                      But what if I add a new entry point? No worries. I just change ifyoulieyougonnadie.php and I'm sorted, plus no 'find and replace'. Hooray!



                      What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined()? ... Hooray! ^_^




                    I found this strategy makes development a lot more fun and a lot less:



                    /**
                    * Hmmm... why is my netbeans debugger only showing a blank white page
                    * for this script (that is being tested outside the framework)?
                    * Later... I just don't understand why my code is not working...
                    * Much later... There are no error messages or anything!
                    * Why is it not working!?!
                    * I HATE PHP!!!
                    *
                    * Scroll back to the top of my 100s of lines of code...
                    * U_U
                    *
                    * Sorry PHP. I didn't mean what I said. I was just upset.
                    */

                    // defined('_JEXEC') or die();

                    class perfectlyWorkingCode {}

                    perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();





                    share|improve this answer

































                      0














                      Do something like:



                      <?php
                      if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
                      header('HTTP/1.0 403 Forbidden');
                      exit('Forbidden');
                      }
                      ?>





                      share|improve this answer


























                      • This will not prevent it from being loaded in the browser.

                        – UnkwnTech
                        Jan 3 '09 at 18:21



















                      0














                      I found this php-only and invariable solution which works both with http and cli :



                      Define a function :



                      function forbidDirectAccess($file) {
                      $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
                      (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
                      }


                      Call the function in the file you want to prevent direct access to :



                      forbidDirectAccess(__FILE__);


                      Most of the solutions given above to this question do not work in Cli mode.






                      share|improve this answer


























                      • where it is supposed to type the URL in CLI mode?

                        – Your Common Sense
                        Apr 6 '11 at 13:48











                      • It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                        – Ka.
                        Apr 6 '11 at 14:51



















                      0














                      You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript.
                      You can place this code in the Body section of your HTML code, so the error shows there.



                      <?
                      if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
                      else { ?>


                      Place your other HTML code here



                      <? } ?>


                      End it like this, so the output of the error will always show within the body section, if that's how you want it to be.






                      share|improve this answer
























                      • I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                        – andreszs
                        Apr 3 '17 at 15:01



















                      0














                      i suggest that don't use of $_SERVER for security reasons .

                      You can use a variable like $root=true; in first file that included another one.

                      and use isset($root) in begin of second file that be included.






                      share|improve this answer































                        0














                        What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access. what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory. you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.



                        well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.



                        Hope this helps






                        share|improve this answer































                          0














                          The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.






                          share|improve this answer































                            0














                            <?php       
                            $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                            if (false !== strpos($url,'.php')) {
                            die ("Direct access not premitted");
                            }
                            ?>





                            share|improve this answer































                              0














                              I didn't find the suggestions with .htaccess so good because it may block
                              other content in that folder which you might want to allow user to access to,
                              this is my solution:



                              $currentFileInfo = pathinfo(__FILE__);
                              $requestInfo = pathinfo($_SERVER['REQUEST_URI']);
                              if($currentFileInfo['basename'] == $requestInfo['basename']){
                              // direct access to file
                              }





                              share|improve this answer































                                0














                                if ( ! defined('BASEPATH')) exit('No direct script access allowed');


                                will do the job smooth






                                share|improve this answer



















                                • 2





                                  Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                  – jimasun
                                  Oct 28 '16 at 15:37













                                • i know there is no need but if any one tries to do so

                                  – Varshaan
                                  Oct 28 '16 at 15:43



















                                0














                                You can use phpMyAdmin Style:



                                /**
                                * block attempts to directly run this script
                                */
                                if (getcwd() == dirname(__FILE__)) {
                                die('Attack stopped');
                                }





                                share|improve this answer































                                  0














                                  this is what google uses in their php examples see here



                                  if (php_sapi_name() != 'cli') {
                                  throw new Exception('This application must be run on the command line.');
                                  }





                                  share|improve this answer



























                                    1 2
                                    next


                                    protected by Taryn Jul 21 '17 at 16:57



                                    Thank you for your interest in this question.
                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                    Would you like to answer one of these unanswered questions instead?














                                    34 Answers
                                    34






                                    active

                                    oldest

                                    votes








                                    34 Answers
                                    34






                                    active

                                    oldest

                                    votes









                                    active

                                    oldest

                                    votes






                                    active

                                    oldest

                                    votes








                                    1 2
                                    next










                                    153














                                    The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:



                                    Deny from all


                                    If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.






                                    share|improve this answer





















                                    • 1





                                      Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

                                      – Alterlife
                                      Jan 3 '09 at 18:23






                                    • 22





                                      if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

                                      – Eineki
                                      Jan 3 '09 at 19:43






                                    • 20





                                      It'd be nice to have an example .htaccess file as part of this answer.

                                      – Graham Lea
                                      Jun 5 '12 at 11:47






                                    • 7





                                      <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

                                      – Dracorat
                                      Sep 27 '12 at 16:53






                                    • 9





                                      @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

                                      – Chuck
                                      Sep 10 '13 at 21:03


















                                    153














                                    The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:



                                    Deny from all


                                    If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.






                                    share|improve this answer





















                                    • 1





                                      Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

                                      – Alterlife
                                      Jan 3 '09 at 18:23






                                    • 22





                                      if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

                                      – Eineki
                                      Jan 3 '09 at 19:43






                                    • 20





                                      It'd be nice to have an example .htaccess file as part of this answer.

                                      – Graham Lea
                                      Jun 5 '12 at 11:47






                                    • 7





                                      <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

                                      – Dracorat
                                      Sep 27 '12 at 16:53






                                    • 9





                                      @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

                                      – Chuck
                                      Sep 10 '13 at 21:03
















                                    153












                                    153








                                    153







                                    The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:



                                    Deny from all


                                    If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.






                                    share|improve this answer















                                    The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:



                                    Deny from all


                                    If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 21 '14 at 7:37

























                                    answered Jan 3 '09 at 18:14









                                    ChuckChuck

                                    203k28268370




                                    203k28268370








                                    • 1





                                      Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

                                      – Alterlife
                                      Jan 3 '09 at 18:23






                                    • 22





                                      if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

                                      – Eineki
                                      Jan 3 '09 at 19:43






                                    • 20





                                      It'd be nice to have an example .htaccess file as part of this answer.

                                      – Graham Lea
                                      Jun 5 '12 at 11:47






                                    • 7





                                      <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

                                      – Dracorat
                                      Sep 27 '12 at 16:53






                                    • 9





                                      @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

                                      – Chuck
                                      Sep 10 '13 at 21:03
















                                    • 1





                                      Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

                                      – Alterlife
                                      Jan 3 '09 at 18:23






                                    • 22





                                      if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

                                      – Eineki
                                      Jan 3 '09 at 19:43






                                    • 20





                                      It'd be nice to have an example .htaccess file as part of this answer.

                                      – Graham Lea
                                      Jun 5 '12 at 11:47






                                    • 7





                                      <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

                                      – Dracorat
                                      Sep 27 '12 at 16:53






                                    • 9





                                      @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

                                      – Chuck
                                      Sep 10 '13 at 21:03










                                    1




                                    1





                                    Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

                                    – Alterlife
                                    Jan 3 '09 at 18:23





                                    Thanks, since I do have full control over the server where I run this app, this is the answer I went with.

                                    – Alterlife
                                    Jan 3 '09 at 18:23




                                    22




                                    22





                                    if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

                                    – Eineki
                                    Jan 3 '09 at 19:43





                                    if you have full control of the server is better if you put the config into a directory directive into the virtual host config file. Apache read it only once on startup, .htaccess is read on every access and slow down the server

                                    – Eineki
                                    Jan 3 '09 at 19:43




                                    20




                                    20





                                    It'd be nice to have an example .htaccess file as part of this answer.

                                    – Graham Lea
                                    Jun 5 '12 at 11:47





                                    It'd be nice to have an example .htaccess file as part of this answer.

                                    – Graham Lea
                                    Jun 5 '12 at 11:47




                                    7




                                    7





                                    <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

                                    – Dracorat
                                    Sep 27 '12 at 16:53





                                    <Files ~ ".inc$"> Order Allow,Deny Deny from All </Files>

                                    – Dracorat
                                    Sep 27 '12 at 16:53




                                    9




                                    9





                                    @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

                                    – Chuck
                                    Sep 10 '13 at 21:03







                                    @James: Also, not everybody feels that Stack Overflow should be a "plz send teh codez" site. If it answers the question clearly, then it is a good answer. Providing an example where none is needed only encourages copy-and-paste coding.

                                    – Chuck
                                    Sep 10 '13 at 21:03















                                    171














                                    Add this to the page that you want to only be included



                                    <?php
                                    if(!defined('MyConst')) {
                                    die('Direct access not permitted');
                                    }
                                    ?>


                                    then on the pages that include it add



                                    <?php
                                    define('MyConst', TRUE);
                                    ?>





                                    share|improve this answer





















                                    • 3





                                      I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

                                      – Mark Davidson
                                      Jan 3 '09 at 18:17






                                    • 3





                                      This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

                                      – UnkwnTech
                                      Jan 3 '09 at 18:20






                                    • 1





                                      Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

                                      – bandi
                                      Jan 4 '09 at 10:05






                                    • 6





                                      Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

                                      – gnud
                                      Jan 4 '09 at 13:24






                                    • 3





                                      @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

                                      – James
                                      Sep 10 '13 at 16:43


















                                    171














                                    Add this to the page that you want to only be included



                                    <?php
                                    if(!defined('MyConst')) {
                                    die('Direct access not permitted');
                                    }
                                    ?>


                                    then on the pages that include it add



                                    <?php
                                    define('MyConst', TRUE);
                                    ?>





                                    share|improve this answer





















                                    • 3





                                      I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

                                      – Mark Davidson
                                      Jan 3 '09 at 18:17






                                    • 3





                                      This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

                                      – UnkwnTech
                                      Jan 3 '09 at 18:20






                                    • 1





                                      Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

                                      – bandi
                                      Jan 4 '09 at 10:05






                                    • 6





                                      Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

                                      – gnud
                                      Jan 4 '09 at 13:24






                                    • 3





                                      @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

                                      – James
                                      Sep 10 '13 at 16:43
















                                    171












                                    171








                                    171







                                    Add this to the page that you want to only be included



                                    <?php
                                    if(!defined('MyConst')) {
                                    die('Direct access not permitted');
                                    }
                                    ?>


                                    then on the pages that include it add



                                    <?php
                                    define('MyConst', TRUE);
                                    ?>





                                    share|improve this answer















                                    Add this to the page that you want to only be included



                                    <?php
                                    if(!defined('MyConst')) {
                                    die('Direct access not permitted');
                                    }
                                    ?>


                                    then on the pages that include it add



                                    <?php
                                    define('MyConst', TRUE);
                                    ?>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Aug 15 '13 at 12:09









                                    Amal Murali

                                    61.6k1299122




                                    61.6k1299122










                                    answered Jan 3 '09 at 18:15









                                    UnkwnTechUnkwnTech

                                    43k58166219




                                    43k58166219








                                    • 3





                                      I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

                                      – Mark Davidson
                                      Jan 3 '09 at 18:17






                                    • 3





                                      This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

                                      – UnkwnTech
                                      Jan 3 '09 at 18:20






                                    • 1





                                      Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

                                      – bandi
                                      Jan 4 '09 at 10:05






                                    • 6





                                      Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

                                      – gnud
                                      Jan 4 '09 at 13:24






                                    • 3





                                      @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

                                      – James
                                      Sep 10 '13 at 16:43
















                                    • 3





                                      I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

                                      – Mark Davidson
                                      Jan 3 '09 at 18:17






                                    • 3





                                      This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

                                      – UnkwnTech
                                      Jan 3 '09 at 18:20






                                    • 1





                                      Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

                                      – bandi
                                      Jan 4 '09 at 10:05






                                    • 6





                                      Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

                                      – gnud
                                      Jan 4 '09 at 13:24






                                    • 3





                                      @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

                                      – James
                                      Sep 10 '13 at 16:43










                                    3




                                    3





                                    I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

                                    – Mark Davidson
                                    Jan 3 '09 at 18:17





                                    I really need to learn to type quicker. This is the same way I would suggest, as its more secure than a method that uses a variable to check. Since with some PHP setups it may be possible to override the variable.

                                    – Mark Davidson
                                    Jan 3 '09 at 18:17




                                    3




                                    3





                                    This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

                                    – UnkwnTech
                                    Jan 3 '09 at 18:20





                                    This is how a few 'mainstream' applications handle it. I know Joomla does it this way and I think Wiki, Wordpress, and others as well.

                                    – UnkwnTech
                                    Jan 3 '09 at 18:20




                                    1




                                    1





                                    Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

                                    – bandi
                                    Jan 4 '09 at 10:05





                                    Maybe the message is too helpful for a hacker (no real user would find these pages), you can simply send a redirect header and stop the php processing.

                                    – bandi
                                    Jan 4 '09 at 10:05




                                    6




                                    6





                                    Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

                                    – gnud
                                    Jan 4 '09 at 13:24





                                    Just send a 404 header and exit -- the error page will look identical to normal 404 pages (at least on Apache).

                                    – gnud
                                    Jan 4 '09 at 13:24




                                    3




                                    3





                                    @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

                                    – James
                                    Sep 10 '13 at 16:43







                                    @Smile.Hunter: this is about blocking access to viewing your include/library script files directly, the answer works. If they created somefile.php on your server and added your define in it, that still doesn't let them directly access the include file. It will let them "include" your library files, but if they get far enough to be creating files on your server and knowing your define/include scripts, you have other issues that likely negate writing their own file with your define in the first place.

                                    – James
                                    Sep 10 '13 at 16:43













                                    104














                                    I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print() vs return()) Here's some modified code:



                                    if(count(get_included_files()) ==1) exit("Direct access not permitted.");


                                    The file being accessed is always an included file, hence the == 1.  






                                    share|improve this answer





















                                    • 10





                                      That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

                                      – Akoi Meexx
                                      Jun 8 '11 at 16:40











                                    • First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

                                      – Jimbo Jonny
                                      Aug 8 '12 at 12:34











                                    • This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

                                      – Anuj
                                      Sep 18 '12 at 20:55






                                    • 3





                                      This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

                                      – jmucchiello
                                      Jun 10 '13 at 1:26











                                    • This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

                                      – whiteatom
                                      Jul 12 '13 at 16:19
















                                    104














                                    I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print() vs return()) Here's some modified code:



                                    if(count(get_included_files()) ==1) exit("Direct access not permitted.");


                                    The file being accessed is always an included file, hence the == 1.  






                                    share|improve this answer





















                                    • 10





                                      That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

                                      – Akoi Meexx
                                      Jun 8 '11 at 16:40











                                    • First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

                                      – Jimbo Jonny
                                      Aug 8 '12 at 12:34











                                    • This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

                                      – Anuj
                                      Sep 18 '12 at 20:55






                                    • 3





                                      This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

                                      – jmucchiello
                                      Jun 10 '13 at 1:26











                                    • This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

                                      – whiteatom
                                      Jul 12 '13 at 16:19














                                    104












                                    104








                                    104







                                    I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print() vs return()) Here's some modified code:



                                    if(count(get_included_files()) ==1) exit("Direct access not permitted.");


                                    The file being accessed is always an included file, hence the == 1.  






                                    share|improve this answer















                                    I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print() vs return()) Here's some modified code:



                                    if(count(get_included_files()) ==1) exit("Direct access not permitted.");


                                    The file being accessed is always an included file, hence the == 1.  







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jan 31 '16 at 16:04









                                    OCDev

                                    1,03821530




                                    1,03821530










                                    answered Jan 3 '09 at 20:09









                                    nullnull

                                    5,27341927




                                    5,27341927








                                    • 10





                                      That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

                                      – Akoi Meexx
                                      Jun 8 '11 at 16:40











                                    • First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

                                      – Jimbo Jonny
                                      Aug 8 '12 at 12:34











                                    • This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

                                      – Anuj
                                      Sep 18 '12 at 20:55






                                    • 3





                                      This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

                                      – jmucchiello
                                      Jun 10 '13 at 1:26











                                    • This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

                                      – whiteatom
                                      Jul 12 '13 at 16:19














                                    • 10





                                      That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

                                      – Akoi Meexx
                                      Jun 8 '11 at 16:40











                                    • First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

                                      – Jimbo Jonny
                                      Aug 8 '12 at 12:34











                                    • This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

                                      – Anuj
                                      Sep 18 '12 at 20:55






                                    • 3





                                      This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

                                      – jmucchiello
                                      Jun 10 '13 at 1:26











                                    • This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

                                      – whiteatom
                                      Jul 12 '13 at 16:19








                                    10




                                    10





                                    That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

                                    – Akoi Meexx
                                    Jun 8 '11 at 16:40





                                    That's actually a hell of an idea, checking the included file count. I wonder which is better: using defines, or using this method? This seems more self-contained.

                                    – Akoi Meexx
                                    Jun 8 '11 at 16:40













                                    First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

                                    – Jimbo Jonny
                                    Aug 8 '12 at 12:34





                                    First time I've ever seen anyone come up with this. I don't know why though, because it seems as self contained as can be, and it's directly measuring what you actually want to know (if is included or not) rather than measuring something assumed to be associated (like a certain constant or a certain location banned by .htaccess). Beautiful.

                                    – Jimbo Jonny
                                    Aug 8 '12 at 12:34













                                    This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

                                    – Anuj
                                    Sep 18 '12 at 20:55





                                    This one is really cool because using .htaccess to block all .php files may not be possible all the time as there can be some files in the same directory those need to be called directly or even by javascripts. Thanks for this great idea!

                                    – Anuj
                                    Sep 18 '12 at 20:55




                                    3




                                    3





                                    This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

                                    – jmucchiello
                                    Jun 10 '13 at 1:26





                                    This only works in PHP5 and up. Pre-PHP5 you want to compare again 0 instead of 1.

                                    – jmucchiello
                                    Jun 10 '13 at 1:26













                                    This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

                                    – whiteatom
                                    Jul 12 '13 at 16:19





                                    This is a really clever solution and allows you to control direct access, not just block it - that's what I like. I usually include unit testing in the files themselves, and this way I can wrap my unit testing in this if statement. Wonder how efficient it is..

                                    – whiteatom
                                    Jul 12 '13 at 16:19











                                    31














                                    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.



                                    I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.






                                    share|improve this answer



















                                    • 2





                                      This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

                                      – Beau Simensen
                                      Jan 3 '09 at 19:29






                                    • 2





                                      In every hosting provider I worked with I always had access to (exactly) one level above the document root.

                                      – Eran Galperin
                                      Jan 3 '09 at 21:21






                                    • 3





                                      At some hosts (including my current one), you can point your domain to whichever folder you wish.

                                      – Dinah
                                      Jun 23 '09 at 15:43






                                    • 1





                                      This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

                                      – MarcoZen
                                      Nov 30 '17 at 15:13











                                    • That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

                                      – Funk Forty Niner
                                      May 8 '18 at 13:22


















                                    31














                                    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.



                                    I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.






                                    share|improve this answer



















                                    • 2





                                      This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

                                      – Beau Simensen
                                      Jan 3 '09 at 19:29






                                    • 2





                                      In every hosting provider I worked with I always had access to (exactly) one level above the document root.

                                      – Eran Galperin
                                      Jan 3 '09 at 21:21






                                    • 3





                                      At some hosts (including my current one), you can point your domain to whichever folder you wish.

                                      – Dinah
                                      Jun 23 '09 at 15:43






                                    • 1





                                      This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

                                      – MarcoZen
                                      Nov 30 '17 at 15:13











                                    • That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

                                      – Funk Forty Niner
                                      May 8 '18 at 13:22
















                                    31












                                    31








                                    31







                                    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.



                                    I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.






                                    share|improve this answer













                                    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.



                                    I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jan 3 '09 at 18:14









                                    Eran GalperinEran Galperin

                                    75.6k20107131




                                    75.6k20107131








                                    • 2





                                      This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

                                      – Beau Simensen
                                      Jan 3 '09 at 19:29






                                    • 2





                                      In every hosting provider I worked with I always had access to (exactly) one level above the document root.

                                      – Eran Galperin
                                      Jan 3 '09 at 21:21






                                    • 3





                                      At some hosts (including my current one), you can point your domain to whichever folder you wish.

                                      – Dinah
                                      Jun 23 '09 at 15:43






                                    • 1





                                      This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

                                      – MarcoZen
                                      Nov 30 '17 at 15:13











                                    • That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

                                      – Funk Forty Niner
                                      May 8 '18 at 13:22
















                                    • 2





                                      This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

                                      – Beau Simensen
                                      Jan 3 '09 at 19:29






                                    • 2





                                      In every hosting provider I worked with I always had access to (exactly) one level above the document root.

                                      – Eran Galperin
                                      Jan 3 '09 at 21:21






                                    • 3





                                      At some hosts (including my current one), you can point your domain to whichever folder you wish.

                                      – Dinah
                                      Jun 23 '09 at 15:43






                                    • 1





                                      This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

                                      – MarcoZen
                                      Nov 30 '17 at 15:13











                                    • That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

                                      – Funk Forty Niner
                                      May 8 '18 at 13:22










                                    2




                                    2





                                    This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

                                    – Beau Simensen
                                    Jan 3 '09 at 19:29





                                    This is a great solution if you are able to do so. I only recently had to start working with shared webhosts and discovered one of many annoyances to be that everything must be inside the docroot.

                                    – Beau Simensen
                                    Jan 3 '09 at 19:29




                                    2




                                    2





                                    In every hosting provider I worked with I always had access to (exactly) one level above the document root.

                                    – Eran Galperin
                                    Jan 3 '09 at 21:21





                                    In every hosting provider I worked with I always had access to (exactly) one level above the document root.

                                    – Eran Galperin
                                    Jan 3 '09 at 21:21




                                    3




                                    3





                                    At some hosts (including my current one), you can point your domain to whichever folder you wish.

                                    – Dinah
                                    Jun 23 '09 at 15:43





                                    At some hosts (including my current one), you can point your domain to whichever folder you wish.

                                    – Dinah
                                    Jun 23 '09 at 15:43




                                    1




                                    1





                                    This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

                                    – MarcoZen
                                    Nov 30 '17 at 15:13





                                    This is a good alternative as well .. using preg_match -> if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution }

                                    – MarcoZen
                                    Nov 30 '17 at 15:13













                                    That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

                                    – Funk Forty Niner
                                    May 8 '18 at 13:22







                                    That url devzone.zend.com/node/view/id/70 is a 404 now. The answer should include the code that was originally used from that non-existant url.

                                    – Funk Forty Niner
                                    May 8 '18 at 13:22













                                    25














                                    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>





                                    share|improve this answer





















                                    • 2





                                      +1 for syntax hints for us lazy types!

                                      – Kyle
                                      Oct 17 '11 at 18:23
















                                    25














                                    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>





                                    share|improve this answer





















                                    • 2





                                      +1 for syntax hints for us lazy types!

                                      – Kyle
                                      Oct 17 '11 at 18:23














                                    25












                                    25








                                    25







                                    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>





                                    share|improve this answer















                                    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>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Oct 18 '12 at 19:12









                                    NullUserException

                                    66.2k22177214




                                    66.2k22177214










                                    answered Jan 3 '09 at 18:48









                                    Kevin LoneyKevin Loney

                                    6,29532332




                                    6,29532332








                                    • 2





                                      +1 for syntax hints for us lazy types!

                                      – Kyle
                                      Oct 17 '11 at 18:23














                                    • 2





                                      +1 for syntax hints for us lazy types!

                                      – Kyle
                                      Oct 17 '11 at 18:23








                                    2




                                    2





                                    +1 for syntax hints for us lazy types!

                                    – Kyle
                                    Oct 17 '11 at 18:23





                                    +1 for syntax hints for us lazy types!

                                    – Kyle
                                    Oct 17 '11 at 18:23











                                    22














                                    1: Checking the count of included files



                                    if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
                                    {
                                    exit('Restricted Access');
                                    }


                                    Logic: PHP exits if the minimum include count isn't met. Note that prior to PHP5, the base page is not considered an include.





                                    2: Defining and verifying a global constant



                                    // In the base page (directly accessed):
                                    define('_DEFVAR', 1);

                                    // In the include files (where direct access isn't permitted):
                                    defined('_DEFVAR') or exit('Restricted Access');


                                    Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.





                                    3: Remote address authorisation



                                    // Call the include from the base page(directly accessed):
                                    $includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

                                    // In the include files (where direct access isn't permitted):
                                    $src = $_SERVER['REMOTE_ADDR']; // Get the source address
                                    $auth = authoriseIP($src); // Authorisation algorithm
                                    if( !$auth ) exit('Restricted Access');


                                    The drawback with this method is isolated execution, unless a session-token provided with the internal request. Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.





                                    4: Token authorisation



                                    Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:



                                    if($key!="serv97602"){header("Location: ".$dart);exit();}


                                    A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.





                                    5: Webserver specific configuration



                                    Most servers allow you to assign permissions for individual files or directories. You could place all your includes in such restricted directories, and have the server configured to deny them.



                                    For example in APACHE, the configuration is stored in the .htaccess file. Tutorial here.



                                    Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers. In such cases where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome. In the end it's best to handle this in code.





                                    6: Placing includes in a secure directory OUTSIDE the site root



                                    Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.



                                    //Your secure dir path based on server file-system
                                    $secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
                                    include($secure_dir."securepage.php");


                                    Logic:




                                    • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.

                                    • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can.

                                    • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.

                                    • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.




                                    Please excuse my unorthodox coding conventions. Any feedback is appreciated.






                                    share|improve this answer


























                                    • i like the number 2

                                      – Baim Wrong
                                      Apr 18 '18 at 14:53
















                                    22














                                    1: Checking the count of included files



                                    if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
                                    {
                                    exit('Restricted Access');
                                    }


                                    Logic: PHP exits if the minimum include count isn't met. Note that prior to PHP5, the base page is not considered an include.





                                    2: Defining and verifying a global constant



                                    // In the base page (directly accessed):
                                    define('_DEFVAR', 1);

                                    // In the include files (where direct access isn't permitted):
                                    defined('_DEFVAR') or exit('Restricted Access');


                                    Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.





                                    3: Remote address authorisation



                                    // Call the include from the base page(directly accessed):
                                    $includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

                                    // In the include files (where direct access isn't permitted):
                                    $src = $_SERVER['REMOTE_ADDR']; // Get the source address
                                    $auth = authoriseIP($src); // Authorisation algorithm
                                    if( !$auth ) exit('Restricted Access');


                                    The drawback with this method is isolated execution, unless a session-token provided with the internal request. Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.





                                    4: Token authorisation



                                    Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:



                                    if($key!="serv97602"){header("Location: ".$dart);exit();}


                                    A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.





                                    5: Webserver specific configuration



                                    Most servers allow you to assign permissions for individual files or directories. You could place all your includes in such restricted directories, and have the server configured to deny them.



                                    For example in APACHE, the configuration is stored in the .htaccess file. Tutorial here.



                                    Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers. In such cases where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome. In the end it's best to handle this in code.





                                    6: Placing includes in a secure directory OUTSIDE the site root



                                    Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.



                                    //Your secure dir path based on server file-system
                                    $secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
                                    include($secure_dir."securepage.php");


                                    Logic:




                                    • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.

                                    • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can.

                                    • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.

                                    • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.




                                    Please excuse my unorthodox coding conventions. Any feedback is appreciated.






                                    share|improve this answer


























                                    • i like the number 2

                                      – Baim Wrong
                                      Apr 18 '18 at 14:53














                                    22












                                    22








                                    22







                                    1: Checking the count of included files



                                    if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
                                    {
                                    exit('Restricted Access');
                                    }


                                    Logic: PHP exits if the minimum include count isn't met. Note that prior to PHP5, the base page is not considered an include.





                                    2: Defining and verifying a global constant



                                    // In the base page (directly accessed):
                                    define('_DEFVAR', 1);

                                    // In the include files (where direct access isn't permitted):
                                    defined('_DEFVAR') or exit('Restricted Access');


                                    Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.





                                    3: Remote address authorisation



                                    // Call the include from the base page(directly accessed):
                                    $includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

                                    // In the include files (where direct access isn't permitted):
                                    $src = $_SERVER['REMOTE_ADDR']; // Get the source address
                                    $auth = authoriseIP($src); // Authorisation algorithm
                                    if( !$auth ) exit('Restricted Access');


                                    The drawback with this method is isolated execution, unless a session-token provided with the internal request. Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.





                                    4: Token authorisation



                                    Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:



                                    if($key!="serv97602"){header("Location: ".$dart);exit();}


                                    A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.





                                    5: Webserver specific configuration



                                    Most servers allow you to assign permissions for individual files or directories. You could place all your includes in such restricted directories, and have the server configured to deny them.



                                    For example in APACHE, the configuration is stored in the .htaccess file. Tutorial here.



                                    Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers. In such cases where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome. In the end it's best to handle this in code.





                                    6: Placing includes in a secure directory OUTSIDE the site root



                                    Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.



                                    //Your secure dir path based on server file-system
                                    $secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
                                    include($secure_dir."securepage.php");


                                    Logic:




                                    • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.

                                    • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can.

                                    • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.

                                    • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.




                                    Please excuse my unorthodox coding conventions. Any feedback is appreciated.






                                    share|improve this answer















                                    1: Checking the count of included files



                                    if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
                                    {
                                    exit('Restricted Access');
                                    }


                                    Logic: PHP exits if the minimum include count isn't met. Note that prior to PHP5, the base page is not considered an include.





                                    2: Defining and verifying a global constant



                                    // In the base page (directly accessed):
                                    define('_DEFVAR', 1);

                                    // In the include files (where direct access isn't permitted):
                                    defined('_DEFVAR') or exit('Restricted Access');


                                    Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.





                                    3: Remote address authorisation



                                    // Call the include from the base page(directly accessed):
                                    $includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

                                    // In the include files (where direct access isn't permitted):
                                    $src = $_SERVER['REMOTE_ADDR']; // Get the source address
                                    $auth = authoriseIP($src); // Authorisation algorithm
                                    if( !$auth ) exit('Restricted Access');


                                    The drawback with this method is isolated execution, unless a session-token provided with the internal request. Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.





                                    4: Token authorisation



                                    Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:



                                    if($key!="serv97602"){header("Location: ".$dart);exit();}


                                    A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.





                                    5: Webserver specific configuration



                                    Most servers allow you to assign permissions for individual files or directories. You could place all your includes in such restricted directories, and have the server configured to deny them.



                                    For example in APACHE, the configuration is stored in the .htaccess file. Tutorial here.



                                    Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers. In such cases where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome. In the end it's best to handle this in code.





                                    6: Placing includes in a secure directory OUTSIDE the site root



                                    Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.



                                    //Your secure dir path based on server file-system
                                    $secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
                                    include($secure_dir."securepage.php");


                                    Logic:




                                    • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.

                                    • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can.

                                    • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.

                                    • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.




                                    Please excuse my unorthodox coding conventions. Any feedback is appreciated.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jun 6 '18 at 22:29

























                                    answered Mar 27 '14 at 5:00









                                    RiARiA

                                    368413




                                    368413













                                    • i like the number 2

                                      – Baim Wrong
                                      Apr 18 '18 at 14:53



















                                    • i like the number 2

                                      – Baim Wrong
                                      Apr 18 '18 at 14:53

















                                    i like the number 2

                                    – Baim Wrong
                                    Apr 18 '18 at 14:53





                                    i like the number 2

                                    – Baim Wrong
                                    Apr 18 '18 at 14:53











                                    14














                                    Actually my advice is to do all of these best practices.




                                    • Put the documents outside the webroot OR in a directory denied access by the webserver
                                      AND

                                    • Use a define in your visible documents that the hidden documents check for:


                                          if (!defined(INCL_FILE_FOO)) {
                                    header('HTTP/1.0 403 Forbidden');
                                    exit;
                                    }


                                    This way if the files become misplaced somehow (an errant ftp operation) they are still protected.






                                    share|improve this answer






























                                      14














                                      Actually my advice is to do all of these best practices.




                                      • Put the documents outside the webroot OR in a directory denied access by the webserver
                                        AND

                                      • Use a define in your visible documents that the hidden documents check for:


                                            if (!defined(INCL_FILE_FOO)) {
                                      header('HTTP/1.0 403 Forbidden');
                                      exit;
                                      }


                                      This way if the files become misplaced somehow (an errant ftp operation) they are still protected.






                                      share|improve this answer




























                                        14












                                        14








                                        14







                                        Actually my advice is to do all of these best practices.




                                        • Put the documents outside the webroot OR in a directory denied access by the webserver
                                          AND

                                        • Use a define in your visible documents that the hidden documents check for:


                                              if (!defined(INCL_FILE_FOO)) {
                                        header('HTTP/1.0 403 Forbidden');
                                        exit;
                                        }


                                        This way if the files become misplaced somehow (an errant ftp operation) they are still protected.






                                        share|improve this answer















                                        Actually my advice is to do all of these best practices.




                                        • Put the documents outside the webroot OR in a directory denied access by the webserver
                                          AND

                                        • Use a define in your visible documents that the hidden documents check for:


                                              if (!defined(INCL_FILE_FOO)) {
                                        header('HTTP/1.0 403 Forbidden');
                                        exit;
                                        }


                                        This way if the files become misplaced somehow (an errant ftp operation) they are still protected.







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 2 '10 at 4:53

























                                        answered Jan 3 '09 at 19:00









                                        jmucchiellojmucchiello

                                        14.4k53558




                                        14.4k53558























                                            7














                                            I had this problem once, solved with:



                                            if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...


                                            but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.






                                            share|improve this answer




























                                              7














                                              I had this problem once, solved with:



                                              if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...


                                              but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.






                                              share|improve this answer


























                                                7












                                                7








                                                7







                                                I had this problem once, solved with:



                                                if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...


                                                but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.






                                                share|improve this answer













                                                I had this problem once, solved with:



                                                if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...


                                                but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Mar 9 '10 at 21:56









                                                matimati

                                                9116




                                                9116























                                                    5














                                                    You'd better build application with one entrance point, i.e. all files should be reached from index.php



                                                    Place this in index.php



                                                    define(A,true);


                                                    This check should run in each linked file (via require or include)



                                                    defined('A') or die(header('HTTP/1.0 403 Forbidden'));





                                                    share|improve this answer




























                                                      5














                                                      You'd better build application with one entrance point, i.e. all files should be reached from index.php



                                                      Place this in index.php



                                                      define(A,true);


                                                      This check should run in each linked file (via require or include)



                                                      defined('A') or die(header('HTTP/1.0 403 Forbidden'));





                                                      share|improve this answer


























                                                        5












                                                        5








                                                        5







                                                        You'd better build application with one entrance point, i.e. all files should be reached from index.php



                                                        Place this in index.php



                                                        define(A,true);


                                                        This check should run in each linked file (via require or include)



                                                        defined('A') or die(header('HTTP/1.0 403 Forbidden'));





                                                        share|improve this answer













                                                        You'd better build application with one entrance point, i.e. all files should be reached from index.php



                                                        Place this in index.php



                                                        define(A,true);


                                                        This check should run in each linked file (via require or include)



                                                        defined('A') or die(header('HTTP/1.0 403 Forbidden'));






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Mar 28 '13 at 23:51









                                                        user2221806user2221806

                                                        5111




                                                        5111























                                                            4














                                                            The easiest way is to set some variable in the file that calls include, such as



                                                            $including = true;


                                                            Then in the file that's being included, check for the variable



                                                            if (!$including) exit("direct access not permitted");





                                                            share|improve this answer



















                                                            • 2





                                                              This is dangerous if register_globals is on.

                                                              – jmucchiello
                                                              Jan 3 '09 at 18:51






                                                            • 24





                                                              PHP is dangerous if register_globals is on.

                                                              – David Precious
                                                              Jan 3 '09 at 18:56











                                                            • @bigpresh super dangerous to be clear.

                                                              – UnkwnTech
                                                              Jan 4 '09 at 20:55
















                                                            4














                                                            The easiest way is to set some variable in the file that calls include, such as



                                                            $including = true;


                                                            Then in the file that's being included, check for the variable



                                                            if (!$including) exit("direct access not permitted");





                                                            share|improve this answer



















                                                            • 2





                                                              This is dangerous if register_globals is on.

                                                              – jmucchiello
                                                              Jan 3 '09 at 18:51






                                                            • 24





                                                              PHP is dangerous if register_globals is on.

                                                              – David Precious
                                                              Jan 3 '09 at 18:56











                                                            • @bigpresh super dangerous to be clear.

                                                              – UnkwnTech
                                                              Jan 4 '09 at 20:55














                                                            4












                                                            4








                                                            4







                                                            The easiest way is to set some variable in the file that calls include, such as



                                                            $including = true;


                                                            Then in the file that's being included, check for the variable



                                                            if (!$including) exit("direct access not permitted");





                                                            share|improve this answer













                                                            The easiest way is to set some variable in the file that calls include, such as



                                                            $including = true;


                                                            Then in the file that's being included, check for the variable



                                                            if (!$including) exit("direct access not permitted");






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Jan 3 '09 at 18:12









                                                            Kyle CroninKyle Cronin

                                                            59.4k38137156




                                                            59.4k38137156








                                                            • 2





                                                              This is dangerous if register_globals is on.

                                                              – jmucchiello
                                                              Jan 3 '09 at 18:51






                                                            • 24





                                                              PHP is dangerous if register_globals is on.

                                                              – David Precious
                                                              Jan 3 '09 at 18:56











                                                            • @bigpresh super dangerous to be clear.

                                                              – UnkwnTech
                                                              Jan 4 '09 at 20:55














                                                            • 2





                                                              This is dangerous if register_globals is on.

                                                              – jmucchiello
                                                              Jan 3 '09 at 18:51






                                                            • 24





                                                              PHP is dangerous if register_globals is on.

                                                              – David Precious
                                                              Jan 3 '09 at 18:56











                                                            • @bigpresh super dangerous to be clear.

                                                              – UnkwnTech
                                                              Jan 4 '09 at 20:55








                                                            2




                                                            2





                                                            This is dangerous if register_globals is on.

                                                            – jmucchiello
                                                            Jan 3 '09 at 18:51





                                                            This is dangerous if register_globals is on.

                                                            – jmucchiello
                                                            Jan 3 '09 at 18:51




                                                            24




                                                            24





                                                            PHP is dangerous if register_globals is on.

                                                            – David Precious
                                                            Jan 3 '09 at 18:56





                                                            PHP is dangerous if register_globals is on.

                                                            – David Precious
                                                            Jan 3 '09 at 18:56













                                                            @bigpresh super dangerous to be clear.

                                                            – UnkwnTech
                                                            Jan 4 '09 at 20:55





                                                            @bigpresh super dangerous to be clear.

                                                            – UnkwnTech
                                                            Jan 4 '09 at 20:55











                                                            4














                                                            What Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files.



                                                            defined('_JEXEC') or die('Restricted access');


                                                            or else



                                                            one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.



                                                            or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.






                                                            share|improve this answer






























                                                              4














                                                              What Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files.



                                                              defined('_JEXEC') or die('Restricted access');


                                                              or else



                                                              one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.



                                                              or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.






                                                              share|improve this answer




























                                                                4












                                                                4








                                                                4







                                                                What Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files.



                                                                defined('_JEXEC') or die('Restricted access');


                                                                or else



                                                                one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.



                                                                or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.






                                                                share|improve this answer















                                                                What Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files.



                                                                defined('_JEXEC') or die('Restricted access');


                                                                or else



                                                                one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.



                                                                or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.







                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Jun 6 '13 at 14:13









                                                                Antony

                                                                13.1k103768




                                                                13.1k103768










                                                                answered May 7 '10 at 13:11









                                                                Pradeesh kumarPradeesh kumar

                                                                411




                                                                411























                                                                    4














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





                                                                    share|improve this answer






























                                                                      4














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





                                                                      share|improve this answer




























                                                                        4












                                                                        4








                                                                        4







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





                                                                        share|improve this answer















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






                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Jun 11 '13 at 1:01

























                                                                        answered Jan 22 '12 at 23:27









                                                                        UnirgyUnirgy

                                                                        844822




                                                                        844822























                                                                            4














                                                                            I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest). Here is what worked for me.



                                                                            if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
                                                                            if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
                                                                            header("Location: /403");
                                                                            exit;
                                                                            }
                                                                            }





                                                                            share|improve this answer






























                                                                              4














                                                                              I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest). Here is what worked for me.



                                                                              if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
                                                                              if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
                                                                              header("Location: /403");
                                                                              exit;
                                                                              }
                                                                              }





                                                                              share|improve this answer




























                                                                                4












                                                                                4








                                                                                4







                                                                                I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest). Here is what worked for me.



                                                                                if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
                                                                                if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
                                                                                header("Location: /403");
                                                                                exit;
                                                                                }
                                                                                }





                                                                                share|improve this answer















                                                                                I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest). Here is what worked for me.



                                                                                if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
                                                                                if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
                                                                                header("Location: /403");
                                                                                exit;
                                                                                }
                                                                                }






                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Nov 8 '17 at 9:18









                                                                                Regolith

                                                                                1,92371829




                                                                                1,92371829










                                                                                answered Nov 8 '17 at 8:27









                                                                                krasenslavovkrasenslavov

                                                                                1151112




                                                                                1151112























                                                                                    3














                                                                                    Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails. They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/. Something like this (not ideal, but you get the idea):



                                                                                    app/
                                                                                    |
                                                                                    +--pub/
                                                                                    |
                                                                                    +--lib/
                                                                                    |
                                                                                    +--conf/
                                                                                    |
                                                                                    +--models/
                                                                                    |
                                                                                    +--views/
                                                                                    |
                                                                                    +--controllers/


                                                                                    You set up your web server to use pub/ as document root. This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet. Another benefit besides security is that everything is in one place.



                                                                                    This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.






                                                                                    share|improve this answer
























                                                                                    • After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                                                                                      – user4108694
                                                                                      Feb 15 '16 at 11:45


















                                                                                    3














                                                                                    Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails. They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/. Something like this (not ideal, but you get the idea):



                                                                                    app/
                                                                                    |
                                                                                    +--pub/
                                                                                    |
                                                                                    +--lib/
                                                                                    |
                                                                                    +--conf/
                                                                                    |
                                                                                    +--models/
                                                                                    |
                                                                                    +--views/
                                                                                    |
                                                                                    +--controllers/


                                                                                    You set up your web server to use pub/ as document root. This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet. Another benefit besides security is that everything is in one place.



                                                                                    This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.






                                                                                    share|improve this answer
























                                                                                    • After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                                                                                      – user4108694
                                                                                      Feb 15 '16 at 11:45
















                                                                                    3












                                                                                    3








                                                                                    3







                                                                                    Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails. They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/. Something like this (not ideal, but you get the idea):



                                                                                    app/
                                                                                    |
                                                                                    +--pub/
                                                                                    |
                                                                                    +--lib/
                                                                                    |
                                                                                    +--conf/
                                                                                    |
                                                                                    +--models/
                                                                                    |
                                                                                    +--views/
                                                                                    |
                                                                                    +--controllers/


                                                                                    You set up your web server to use pub/ as document root. This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet. Another benefit besides security is that everything is in one place.



                                                                                    This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.






                                                                                    share|improve this answer













                                                                                    Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails. They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/. Something like this (not ideal, but you get the idea):



                                                                                    app/
                                                                                    |
                                                                                    +--pub/
                                                                                    |
                                                                                    +--lib/
                                                                                    |
                                                                                    +--conf/
                                                                                    |
                                                                                    +--models/
                                                                                    |
                                                                                    +--views/
                                                                                    |
                                                                                    +--controllers/


                                                                                    You set up your web server to use pub/ as document root. This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet. Another benefit besides security is that everything is in one place.



                                                                                    This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.







                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Jan 4 '09 at 13:06









                                                                                    bandibandi

                                                                                    3,68712124




                                                                                    3,68712124













                                                                                    • After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                                                                                      – user4108694
                                                                                      Feb 15 '16 at 11:45





















                                                                                    • After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                                                                                      – user4108694
                                                                                      Feb 15 '16 at 11:45



















                                                                                    After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                                                                                    – user4108694
                                                                                    Feb 15 '16 at 11:45







                                                                                    After a long time I just want to comment that the model you describe above called MVC (Model - View - Controller) model. If you please, check google and add some more info to your answer. Also MVC support not only Ruby on Rails and ASP.NET applications, but also PHP ( see Lavarel, CakePHP).

                                                                                    – user4108694
                                                                                    Feb 15 '16 at 11:45













                                                                                    2














                                                                                    If more precisely, you should use this condition:



                                                                                    if (array_search(__FILE__, get_included_files()) === 0) {
                                                                                    echo 'direct access';
                                                                                    }
                                                                                    else {
                                                                                    echo 'included';
                                                                                    }


                                                                                    get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array).
                                                                                    So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.






                                                                                    share|improve this answer




























                                                                                      2














                                                                                      If more precisely, you should use this condition:



                                                                                      if (array_search(__FILE__, get_included_files()) === 0) {
                                                                                      echo 'direct access';
                                                                                      }
                                                                                      else {
                                                                                      echo 'included';
                                                                                      }


                                                                                      get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array).
                                                                                      So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.






                                                                                      share|improve this answer


























                                                                                        2












                                                                                        2








                                                                                        2







                                                                                        If more precisely, you should use this condition:



                                                                                        if (array_search(__FILE__, get_included_files()) === 0) {
                                                                                        echo 'direct access';
                                                                                        }
                                                                                        else {
                                                                                        echo 'included';
                                                                                        }


                                                                                        get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array).
                                                                                        So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.






                                                                                        share|improve this answer













                                                                                        If more precisely, you should use this condition:



                                                                                        if (array_search(__FILE__, get_included_files()) === 0) {
                                                                                        echo 'direct access';
                                                                                        }
                                                                                        else {
                                                                                        echo 'included';
                                                                                        }


                                                                                        get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array).
                                                                                        So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered May 8 '15 at 21:37









                                                                                        Oleg LokshynOleg Lokshyn

                                                                                        106110




                                                                                        106110























                                                                                            1














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


                                                                                            place the code above in the top of your included php file.



                                                                                            ex:



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

                                                                                            // do something
                                                                                            ?>





                                                                                            share|improve this answer
























                                                                                            • eregi is deprecated now. Replace with preg_match as shown below...

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:11













                                                                                            • if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:12
















                                                                                            1














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


                                                                                            place the code above in the top of your included php file.



                                                                                            ex:



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

                                                                                            // do something
                                                                                            ?>





                                                                                            share|improve this answer
























                                                                                            • eregi is deprecated now. Replace with preg_match as shown below...

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:11













                                                                                            • if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:12














                                                                                            1












                                                                                            1








                                                                                            1







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


                                                                                            place the code above in the top of your included php file.



                                                                                            ex:



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

                                                                                            // do something
                                                                                            ?>





                                                                                            share|improve this answer













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


                                                                                            place the code above in the top of your included php file.



                                                                                            ex:



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

                                                                                            // do something
                                                                                            ?>






                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered May 7 '10 at 13:00









                                                                                            Blogging TipsBlogging Tips

                                                                                            111




                                                                                            111













                                                                                            • eregi is deprecated now. Replace with preg_match as shown below...

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:11













                                                                                            • if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:12



















                                                                                            • eregi is deprecated now. Replace with preg_match as shown below...

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:11













                                                                                            • if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                                                                                              – MarcoZen
                                                                                              Nov 30 '17 at 15:12

















                                                                                            eregi is deprecated now. Replace with preg_match as shown below...

                                                                                            – MarcoZen
                                                                                            Nov 30 '17 at 15:11







                                                                                            eregi is deprecated now. Replace with preg_match as shown below...

                                                                                            – MarcoZen
                                                                                            Nov 30 '17 at 15:11















                                                                                            if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                                                                                            – MarcoZen
                                                                                            Nov 30 '17 at 15:12





                                                                                            if ( preg_match("~globalfile.php~i", $_SERVER['PHP_SELF'] ) ) { die('<h3 style="color:red"> Appliance Security Alert - Direct Access Disallowed! Your IP has been logged !<h3>'); // Stop further execution } whre ~ is the delimiter

                                                                                            – MarcoZen
                                                                                            Nov 30 '17 at 15:12











                                                                                            1














                                                                                            The following code is used in the Flatnux CMS (http://flatnux.altervista.org):



                                                                                            if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
                                                                                            {
                                                                                            header("Location: ../../index.php");
                                                                                            die("...");
                                                                                            }





                                                                                            share|improve this answer




























                                                                                              1














                                                                                              The following code is used in the Flatnux CMS (http://flatnux.altervista.org):



                                                                                              if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
                                                                                              {
                                                                                              header("Location: ../../index.php");
                                                                                              die("...");
                                                                                              }





                                                                                              share|improve this answer


























                                                                                                1












                                                                                                1








                                                                                                1







                                                                                                The following code is used in the Flatnux CMS (http://flatnux.altervista.org):



                                                                                                if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
                                                                                                {
                                                                                                header("Location: ../../index.php");
                                                                                                die("...");
                                                                                                }





                                                                                                share|improve this answer













                                                                                                The following code is used in the Flatnux CMS (http://flatnux.altervista.org):



                                                                                                if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
                                                                                                {
                                                                                                header("Location: ../../index.php");
                                                                                                die("...");
                                                                                                }






                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Jul 18 '10 at 0:44









                                                                                                JohnRDOrazioJohnRDOrazio

                                                                                                405618




                                                                                                405618























                                                                                                    1














                                                                                                    if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };





                                                                                                    share|improve this answer




























                                                                                                      1














                                                                                                      if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };





                                                                                                      share|improve this answer


























                                                                                                        1












                                                                                                        1








                                                                                                        1







                                                                                                        if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };





                                                                                                        share|improve this answer













                                                                                                        if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };






                                                                                                        share|improve this answer












                                                                                                        share|improve this answer



                                                                                                        share|improve this answer










                                                                                                        answered Oct 1 '13 at 11:17









                                                                                                        andyandy

                                                                                                        18913




                                                                                                        18913























                                                                                                            1














                                                                                                            My answer is somewhat different in approach but includes many of the answers provided here. I would recommend a multipronged approach:




                                                                                                            1. .htaccess and Apache restrictions for sure

                                                                                                            2. defined('_SOMECONSTANT') or die('Hackers! Be gone!');


                                                                                                            HOWEVER the defined or die approach has a number of failings. Firstly, it is a real pain in the assumptions to test and debug with. Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind. "Find and replace!" you say. Yes, but how sure are you that it is written exactly the same everywhere, hmmm? Now multiply that with thousands of files... o.O



                                                                                                            And then there's .htaccess. What happens if your code is distributed onto sites where the administrator is not so scrupulous? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.



                                                                                                            So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".



                                                                                                            What I suggest is:




                                                                                                            1. Before any of your scripts require('ifyoulieyougonnadie.php'); (not include() and as a replacement for defined or die)


                                                                                                            2. In ifyoulieyougonnadie.php, do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403, etc.



                                                                                                              I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things. If the request to ifyoulieyougonnadie.php doesn't come from one of those two files, I know shenanigans are being undertaken!



                                                                                                              But what if I add a new entry point? No worries. I just change ifyoulieyougonnadie.php and I'm sorted, plus no 'find and replace'. Hooray!



                                                                                                              What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined()? ... Hooray! ^_^




                                                                                                            I found this strategy makes development a lot more fun and a lot less:



                                                                                                            /**
                                                                                                            * Hmmm... why is my netbeans debugger only showing a blank white page
                                                                                                            * for this script (that is being tested outside the framework)?
                                                                                                            * Later... I just don't understand why my code is not working...
                                                                                                            * Much later... There are no error messages or anything!
                                                                                                            * Why is it not working!?!
                                                                                                            * I HATE PHP!!!
                                                                                                            *
                                                                                                            * Scroll back to the top of my 100s of lines of code...
                                                                                                            * U_U
                                                                                                            *
                                                                                                            * Sorry PHP. I didn't mean what I said. I was just upset.
                                                                                                            */

                                                                                                            // defined('_JEXEC') or die();

                                                                                                            class perfectlyWorkingCode {}

                                                                                                            perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();





                                                                                                            share|improve this answer






























                                                                                                              1














                                                                                                              My answer is somewhat different in approach but includes many of the answers provided here. I would recommend a multipronged approach:




                                                                                                              1. .htaccess and Apache restrictions for sure

                                                                                                              2. defined('_SOMECONSTANT') or die('Hackers! Be gone!');


                                                                                                              HOWEVER the defined or die approach has a number of failings. Firstly, it is a real pain in the assumptions to test and debug with. Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind. "Find and replace!" you say. Yes, but how sure are you that it is written exactly the same everywhere, hmmm? Now multiply that with thousands of files... o.O



                                                                                                              And then there's .htaccess. What happens if your code is distributed onto sites where the administrator is not so scrupulous? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.



                                                                                                              So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".



                                                                                                              What I suggest is:




                                                                                                              1. Before any of your scripts require('ifyoulieyougonnadie.php'); (not include() and as a replacement for defined or die)


                                                                                                              2. In ifyoulieyougonnadie.php, do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403, etc.



                                                                                                                I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things. If the request to ifyoulieyougonnadie.php doesn't come from one of those two files, I know shenanigans are being undertaken!



                                                                                                                But what if I add a new entry point? No worries. I just change ifyoulieyougonnadie.php and I'm sorted, plus no 'find and replace'. Hooray!



                                                                                                                What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined()? ... Hooray! ^_^




                                                                                                              I found this strategy makes development a lot more fun and a lot less:



                                                                                                              /**
                                                                                                              * Hmmm... why is my netbeans debugger only showing a blank white page
                                                                                                              * for this script (that is being tested outside the framework)?
                                                                                                              * Later... I just don't understand why my code is not working...
                                                                                                              * Much later... There are no error messages or anything!
                                                                                                              * Why is it not working!?!
                                                                                                              * I HATE PHP!!!
                                                                                                              *
                                                                                                              * Scroll back to the top of my 100s of lines of code...
                                                                                                              * U_U
                                                                                                              *
                                                                                                              * Sorry PHP. I didn't mean what I said. I was just upset.
                                                                                                              */

                                                                                                              // defined('_JEXEC') or die();

                                                                                                              class perfectlyWorkingCode {}

                                                                                                              perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();





                                                                                                              share|improve this answer




























                                                                                                                1












                                                                                                                1








                                                                                                                1







                                                                                                                My answer is somewhat different in approach but includes many of the answers provided here. I would recommend a multipronged approach:




                                                                                                                1. .htaccess and Apache restrictions for sure

                                                                                                                2. defined('_SOMECONSTANT') or die('Hackers! Be gone!');


                                                                                                                HOWEVER the defined or die approach has a number of failings. Firstly, it is a real pain in the assumptions to test and debug with. Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind. "Find and replace!" you say. Yes, but how sure are you that it is written exactly the same everywhere, hmmm? Now multiply that with thousands of files... o.O



                                                                                                                And then there's .htaccess. What happens if your code is distributed onto sites where the administrator is not so scrupulous? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.



                                                                                                                So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".



                                                                                                                What I suggest is:




                                                                                                                1. Before any of your scripts require('ifyoulieyougonnadie.php'); (not include() and as a replacement for defined or die)


                                                                                                                2. In ifyoulieyougonnadie.php, do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403, etc.



                                                                                                                  I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things. If the request to ifyoulieyougonnadie.php doesn't come from one of those two files, I know shenanigans are being undertaken!



                                                                                                                  But what if I add a new entry point? No worries. I just change ifyoulieyougonnadie.php and I'm sorted, plus no 'find and replace'. Hooray!



                                                                                                                  What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined()? ... Hooray! ^_^




                                                                                                                I found this strategy makes development a lot more fun and a lot less:



                                                                                                                /**
                                                                                                                * Hmmm... why is my netbeans debugger only showing a blank white page
                                                                                                                * for this script (that is being tested outside the framework)?
                                                                                                                * Later... I just don't understand why my code is not working...
                                                                                                                * Much later... There are no error messages or anything!
                                                                                                                * Why is it not working!?!
                                                                                                                * I HATE PHP!!!
                                                                                                                *
                                                                                                                * Scroll back to the top of my 100s of lines of code...
                                                                                                                * U_U
                                                                                                                *
                                                                                                                * Sorry PHP. I didn't mean what I said. I was just upset.
                                                                                                                */

                                                                                                                // defined('_JEXEC') or die();

                                                                                                                class perfectlyWorkingCode {}

                                                                                                                perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();





                                                                                                                share|improve this answer















                                                                                                                My answer is somewhat different in approach but includes many of the answers provided here. I would recommend a multipronged approach:




                                                                                                                1. .htaccess and Apache restrictions for sure

                                                                                                                2. defined('_SOMECONSTANT') or die('Hackers! Be gone!');


                                                                                                                HOWEVER the defined or die approach has a number of failings. Firstly, it is a real pain in the assumptions to test and debug with. Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind. "Find and replace!" you say. Yes, but how sure are you that it is written exactly the same everywhere, hmmm? Now multiply that with thousands of files... o.O



                                                                                                                And then there's .htaccess. What happens if your code is distributed onto sites where the administrator is not so scrupulous? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.



                                                                                                                So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".



                                                                                                                What I suggest is:




                                                                                                                1. Before any of your scripts require('ifyoulieyougonnadie.php'); (not include() and as a replacement for defined or die)


                                                                                                                2. In ifyoulieyougonnadie.php, do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403, etc.



                                                                                                                  I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things. If the request to ifyoulieyougonnadie.php doesn't come from one of those two files, I know shenanigans are being undertaken!



                                                                                                                  But what if I add a new entry point? No worries. I just change ifyoulieyougonnadie.php and I'm sorted, plus no 'find and replace'. Hooray!



                                                                                                                  What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined()? ... Hooray! ^_^




                                                                                                                I found this strategy makes development a lot more fun and a lot less:



                                                                                                                /**
                                                                                                                * Hmmm... why is my netbeans debugger only showing a blank white page
                                                                                                                * for this script (that is being tested outside the framework)?
                                                                                                                * Later... I just don't understand why my code is not working...
                                                                                                                * Much later... There are no error messages or anything!
                                                                                                                * Why is it not working!?!
                                                                                                                * I HATE PHP!!!
                                                                                                                *
                                                                                                                * Scroll back to the top of my 100s of lines of code...
                                                                                                                * U_U
                                                                                                                *
                                                                                                                * Sorry PHP. I didn't mean what I said. I was just upset.
                                                                                                                */

                                                                                                                // defined('_JEXEC') or die();

                                                                                                                class perfectlyWorkingCode {}

                                                                                                                perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();






                                                                                                                share|improve this answer














                                                                                                                share|improve this answer



                                                                                                                share|improve this answer








                                                                                                                edited Dec 6 '13 at 11:24

























                                                                                                                answered Dec 6 '13 at 9:48









                                                                                                                Just Plain HighJust Plain High

                                                                                                                772621




                                                                                                                772621























                                                                                                                    0














                                                                                                                    Do something like:



                                                                                                                    <?php
                                                                                                                    if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
                                                                                                                    header('HTTP/1.0 403 Forbidden');
                                                                                                                    exit('Forbidden');
                                                                                                                    }
                                                                                                                    ?>





                                                                                                                    share|improve this answer


























                                                                                                                    • This will not prevent it from being loaded in the browser.

                                                                                                                      – UnkwnTech
                                                                                                                      Jan 3 '09 at 18:21
















                                                                                                                    0














                                                                                                                    Do something like:



                                                                                                                    <?php
                                                                                                                    if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
                                                                                                                    header('HTTP/1.0 403 Forbidden');
                                                                                                                    exit('Forbidden');
                                                                                                                    }
                                                                                                                    ?>





                                                                                                                    share|improve this answer


























                                                                                                                    • This will not prevent it from being loaded in the browser.

                                                                                                                      – UnkwnTech
                                                                                                                      Jan 3 '09 at 18:21














                                                                                                                    0












                                                                                                                    0








                                                                                                                    0







                                                                                                                    Do something like:



                                                                                                                    <?php
                                                                                                                    if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
                                                                                                                    header('HTTP/1.0 403 Forbidden');
                                                                                                                    exit('Forbidden');
                                                                                                                    }
                                                                                                                    ?>





                                                                                                                    share|improve this answer















                                                                                                                    Do something like:



                                                                                                                    <?php
                                                                                                                    if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
                                                                                                                    header('HTTP/1.0 403 Forbidden');
                                                                                                                    exit('Forbidden');
                                                                                                                    }
                                                                                                                    ?>






                                                                                                                    share|improve this answer














                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer








                                                                                                                    edited Jan 3 '09 at 18:24

























                                                                                                                    answered Jan 3 '09 at 18:18









                                                                                                                    kmkaplankmkaplan

                                                                                                                    16k34459




                                                                                                                    16k34459













                                                                                                                    • This will not prevent it from being loaded in the browser.

                                                                                                                      – UnkwnTech
                                                                                                                      Jan 3 '09 at 18:21



















                                                                                                                    • This will not prevent it from being loaded in the browser.

                                                                                                                      – UnkwnTech
                                                                                                                      Jan 3 '09 at 18:21

















                                                                                                                    This will not prevent it from being loaded in the browser.

                                                                                                                    – UnkwnTech
                                                                                                                    Jan 3 '09 at 18:21





                                                                                                                    This will not prevent it from being loaded in the browser.

                                                                                                                    – UnkwnTech
                                                                                                                    Jan 3 '09 at 18:21











                                                                                                                    0














                                                                                                                    I found this php-only and invariable solution which works both with http and cli :



                                                                                                                    Define a function :



                                                                                                                    function forbidDirectAccess($file) {
                                                                                                                    $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
                                                                                                                    (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
                                                                                                                    }


                                                                                                                    Call the function in the file you want to prevent direct access to :



                                                                                                                    forbidDirectAccess(__FILE__);


                                                                                                                    Most of the solutions given above to this question do not work in Cli mode.






                                                                                                                    share|improve this answer


























                                                                                                                    • where it is supposed to type the URL in CLI mode?

                                                                                                                      – Your Common Sense
                                                                                                                      Apr 6 '11 at 13:48











                                                                                                                    • It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                                                                                                                      – Ka.
                                                                                                                      Apr 6 '11 at 14:51
















                                                                                                                    0














                                                                                                                    I found this php-only and invariable solution which works both with http and cli :



                                                                                                                    Define a function :



                                                                                                                    function forbidDirectAccess($file) {
                                                                                                                    $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
                                                                                                                    (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
                                                                                                                    }


                                                                                                                    Call the function in the file you want to prevent direct access to :



                                                                                                                    forbidDirectAccess(__FILE__);


                                                                                                                    Most of the solutions given above to this question do not work in Cli mode.






                                                                                                                    share|improve this answer


























                                                                                                                    • where it is supposed to type the URL in CLI mode?

                                                                                                                      – Your Common Sense
                                                                                                                      Apr 6 '11 at 13:48











                                                                                                                    • It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                                                                                                                      – Ka.
                                                                                                                      Apr 6 '11 at 14:51














                                                                                                                    0












                                                                                                                    0








                                                                                                                    0







                                                                                                                    I found this php-only and invariable solution which works both with http and cli :



                                                                                                                    Define a function :



                                                                                                                    function forbidDirectAccess($file) {
                                                                                                                    $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
                                                                                                                    (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
                                                                                                                    }


                                                                                                                    Call the function in the file you want to prevent direct access to :



                                                                                                                    forbidDirectAccess(__FILE__);


                                                                                                                    Most of the solutions given above to this question do not work in Cli mode.






                                                                                                                    share|improve this answer















                                                                                                                    I found this php-only and invariable solution which works both with http and cli :



                                                                                                                    Define a function :



                                                                                                                    function forbidDirectAccess($file) {
                                                                                                                    $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
                                                                                                                    (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
                                                                                                                    }


                                                                                                                    Call the function in the file you want to prevent direct access to :



                                                                                                                    forbidDirectAccess(__FILE__);


                                                                                                                    Most of the solutions given above to this question do not work in Cli mode.







                                                                                                                    share|improve this answer














                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer








                                                                                                                    edited Apr 6 '11 at 13:45

























                                                                                                                    answered Feb 16 '11 at 16:08









                                                                                                                    Ka.Ka.

                                                                                                                    80511015




                                                                                                                    80511015













                                                                                                                    • where it is supposed to type the URL in CLI mode?

                                                                                                                      – Your Common Sense
                                                                                                                      Apr 6 '11 at 13:48











                                                                                                                    • It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                                                                                                                      – Ka.
                                                                                                                      Apr 6 '11 at 14:51



















                                                                                                                    • where it is supposed to type the URL in CLI mode?

                                                                                                                      – Your Common Sense
                                                                                                                      Apr 6 '11 at 13:48











                                                                                                                    • It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                                                                                                                      – Ka.
                                                                                                                      Apr 6 '11 at 14:51

















                                                                                                                    where it is supposed to type the URL in CLI mode?

                                                                                                                    – Your Common Sense
                                                                                                                    Apr 6 '11 at 13:48





                                                                                                                    where it is supposed to type the URL in CLI mode?

                                                                                                                    – Your Common Sense
                                                                                                                    Apr 6 '11 at 13:48













                                                                                                                    It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                                                                                                                    – Ka.
                                                                                                                    Apr 6 '11 at 14:51





                                                                                                                    It is just to prevent the launch of php script/inlude in cli mode. Can be useful in a project with multiple developers.

                                                                                                                    – Ka.
                                                                                                                    Apr 6 '11 at 14:51











                                                                                                                    0














                                                                                                                    You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript.
                                                                                                                    You can place this code in the Body section of your HTML code, so the error shows there.



                                                                                                                    <?
                                                                                                                    if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
                                                                                                                    else { ?>


                                                                                                                    Place your other HTML code here



                                                                                                                    <? } ?>


                                                                                                                    End it like this, so the output of the error will always show within the body section, if that's how you want it to be.






                                                                                                                    share|improve this answer
























                                                                                                                    • I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                                                                                                                      – andreszs
                                                                                                                      Apr 3 '17 at 15:01
















                                                                                                                    0














                                                                                                                    You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript.
                                                                                                                    You can place this code in the Body section of your HTML code, so the error shows there.



                                                                                                                    <?
                                                                                                                    if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
                                                                                                                    else { ?>


                                                                                                                    Place your other HTML code here



                                                                                                                    <? } ?>


                                                                                                                    End it like this, so the output of the error will always show within the body section, if that's how you want it to be.






                                                                                                                    share|improve this answer
























                                                                                                                    • I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                                                                                                                      – andreszs
                                                                                                                      Apr 3 '17 at 15:01














                                                                                                                    0












                                                                                                                    0








                                                                                                                    0







                                                                                                                    You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript.
                                                                                                                    You can place this code in the Body section of your HTML code, so the error shows there.



                                                                                                                    <?
                                                                                                                    if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
                                                                                                                    else { ?>


                                                                                                                    Place your other HTML code here



                                                                                                                    <? } ?>


                                                                                                                    End it like this, so the output of the error will always show within the body section, if that's how you want it to be.






                                                                                                                    share|improve this answer













                                                                                                                    You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript.
                                                                                                                    You can place this code in the Body section of your HTML code, so the error shows there.



                                                                                                                    <?
                                                                                                                    if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
                                                                                                                    else { ?>


                                                                                                                    Place your other HTML code here



                                                                                                                    <? } ?>


                                                                                                                    End it like this, so the output of the error will always show within the body section, if that's how you want it to be.







                                                                                                                    share|improve this answer












                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer










                                                                                                                    answered Sep 10 '11 at 0:53









                                                                                                                    Charming PrinceCharming Prince

                                                                                                                    421211




                                                                                                                    421211













                                                                                                                    • I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                                                                                                                      – andreszs
                                                                                                                      Apr 3 '17 at 15:01



















                                                                                                                    • I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                                                                                                                      – andreszs
                                                                                                                      Apr 3 '17 at 15:01

















                                                                                                                    I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                                                                                                                    – andreszs
                                                                                                                    Apr 3 '17 at 15:01





                                                                                                                    I understand that all HTTP_* server headers are not to be trusted, so you better not use this method.

                                                                                                                    – andreszs
                                                                                                                    Apr 3 '17 at 15:01











                                                                                                                    0














                                                                                                                    i suggest that don't use of $_SERVER for security reasons .

                                                                                                                    You can use a variable like $root=true; in first file that included another one.

                                                                                                                    and use isset($root) in begin of second file that be included.






                                                                                                                    share|improve this answer




























                                                                                                                      0














                                                                                                                      i suggest that don't use of $_SERVER for security reasons .

                                                                                                                      You can use a variable like $root=true; in first file that included another one.

                                                                                                                      and use isset($root) in begin of second file that be included.






                                                                                                                      share|improve this answer


























                                                                                                                        0












                                                                                                                        0








                                                                                                                        0







                                                                                                                        i suggest that don't use of $_SERVER for security reasons .

                                                                                                                        You can use a variable like $root=true; in first file that included another one.

                                                                                                                        and use isset($root) in begin of second file that be included.






                                                                                                                        share|improve this answer













                                                                                                                        i suggest that don't use of $_SERVER for security reasons .

                                                                                                                        You can use a variable like $root=true; in first file that included another one.

                                                                                                                        and use isset($root) in begin of second file that be included.







                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered Apr 23 '12 at 15:56









                                                                                                                        Mohamad RostamiMohamad Rostami

                                                                                                                        2,8822735




                                                                                                                        2,8822735























                                                                                                                            0














                                                                                                                            What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access. what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory. you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.



                                                                                                                            well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.



                                                                                                                            Hope this helps






                                                                                                                            share|improve this answer




























                                                                                                                              0














                                                                                                                              What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access. what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory. you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.



                                                                                                                              well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.



                                                                                                                              Hope this helps






                                                                                                                              share|improve this answer


























                                                                                                                                0












                                                                                                                                0








                                                                                                                                0







                                                                                                                                What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access. what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory. you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.



                                                                                                                                well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.



                                                                                                                                Hope this helps






                                                                                                                                share|improve this answer













                                                                                                                                What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access. what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory. you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.



                                                                                                                                well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.



                                                                                                                                Hope this helps







                                                                                                                                share|improve this answer












                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer










                                                                                                                                answered Feb 5 '13 at 17:30









                                                                                                                                RohitGRohitG

                                                                                                                                216




                                                                                                                                216























                                                                                                                                    0














                                                                                                                                    The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.






                                                                                                                                    share|improve this answer




























                                                                                                                                      0














                                                                                                                                      The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.






                                                                                                                                      share|improve this answer


























                                                                                                                                        0












                                                                                                                                        0








                                                                                                                                        0







                                                                                                                                        The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.






                                                                                                                                        share|improve this answer













                                                                                                                                        The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.







                                                                                                                                        share|improve this answer












                                                                                                                                        share|improve this answer



                                                                                                                                        share|improve this answer










                                                                                                                                        answered Aug 14 '13 at 14:34







                                                                                                                                        user1391838






























                                                                                                                                            0














                                                                                                                                            <?php       
                                                                                                                                            $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                                                                                                                                            if (false !== strpos($url,'.php')) {
                                                                                                                                            die ("Direct access not premitted");
                                                                                                                                            }
                                                                                                                                            ?>





                                                                                                                                            share|improve this answer




























                                                                                                                                              0














                                                                                                                                              <?php       
                                                                                                                                              $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                                                                                                                                              if (false !== strpos($url,'.php')) {
                                                                                                                                              die ("Direct access not premitted");
                                                                                                                                              }
                                                                                                                                              ?>





                                                                                                                                              share|improve this answer


























                                                                                                                                                0












                                                                                                                                                0








                                                                                                                                                0







                                                                                                                                                <?php       
                                                                                                                                                $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                                                                                                                                                if (false !== strpos($url,'.php')) {
                                                                                                                                                die ("Direct access not premitted");
                                                                                                                                                }
                                                                                                                                                ?>





                                                                                                                                                share|improve this answer













                                                                                                                                                <?php       
                                                                                                                                                $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                                                                                                                                                if (false !== strpos($url,'.php')) {
                                                                                                                                                die ("Direct access not premitted");
                                                                                                                                                }
                                                                                                                                                ?>






                                                                                                                                                share|improve this answer












                                                                                                                                                share|improve this answer



                                                                                                                                                share|improve this answer










                                                                                                                                                answered Mar 8 '14 at 4:42









                                                                                                                                                Matt BettiolMatt Bettiol

                                                                                                                                                84118




                                                                                                                                                84118























                                                                                                                                                    0














                                                                                                                                                    I didn't find the suggestions with .htaccess so good because it may block
                                                                                                                                                    other content in that folder which you might want to allow user to access to,
                                                                                                                                                    this is my solution:



                                                                                                                                                    $currentFileInfo = pathinfo(__FILE__);
                                                                                                                                                    $requestInfo = pathinfo($_SERVER['REQUEST_URI']);
                                                                                                                                                    if($currentFileInfo['basename'] == $requestInfo['basename']){
                                                                                                                                                    // direct access to file
                                                                                                                                                    }





                                                                                                                                                    share|improve this answer




























                                                                                                                                                      0














                                                                                                                                                      I didn't find the suggestions with .htaccess so good because it may block
                                                                                                                                                      other content in that folder which you might want to allow user to access to,
                                                                                                                                                      this is my solution:



                                                                                                                                                      $currentFileInfo = pathinfo(__FILE__);
                                                                                                                                                      $requestInfo = pathinfo($_SERVER['REQUEST_URI']);
                                                                                                                                                      if($currentFileInfo['basename'] == $requestInfo['basename']){
                                                                                                                                                      // direct access to file
                                                                                                                                                      }





                                                                                                                                                      share|improve this answer


























                                                                                                                                                        0












                                                                                                                                                        0








                                                                                                                                                        0







                                                                                                                                                        I didn't find the suggestions with .htaccess so good because it may block
                                                                                                                                                        other content in that folder which you might want to allow user to access to,
                                                                                                                                                        this is my solution:



                                                                                                                                                        $currentFileInfo = pathinfo(__FILE__);
                                                                                                                                                        $requestInfo = pathinfo($_SERVER['REQUEST_URI']);
                                                                                                                                                        if($currentFileInfo['basename'] == $requestInfo['basename']){
                                                                                                                                                        // direct access to file
                                                                                                                                                        }





                                                                                                                                                        share|improve this answer













                                                                                                                                                        I didn't find the suggestions with .htaccess so good because it may block
                                                                                                                                                        other content in that folder which you might want to allow user to access to,
                                                                                                                                                        this is my solution:



                                                                                                                                                        $currentFileInfo = pathinfo(__FILE__);
                                                                                                                                                        $requestInfo = pathinfo($_SERVER['REQUEST_URI']);
                                                                                                                                                        if($currentFileInfo['basename'] == $requestInfo['basename']){
                                                                                                                                                        // direct access to file
                                                                                                                                                        }






                                                                                                                                                        share|improve this answer












                                                                                                                                                        share|improve this answer



                                                                                                                                                        share|improve this answer










                                                                                                                                                        answered Sep 10 '15 at 8:17









                                                                                                                                                        talsibonytalsibony

                                                                                                                                                        4,31643137




                                                                                                                                                        4,31643137























                                                                                                                                                            0














                                                                                                                                                            if ( ! defined('BASEPATH')) exit('No direct script access allowed');


                                                                                                                                                            will do the job smooth






                                                                                                                                                            share|improve this answer



















                                                                                                                                                            • 2





                                                                                                                                                              Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                                                                                                                                              – jimasun
                                                                                                                                                              Oct 28 '16 at 15:37













                                                                                                                                                            • i know there is no need but if any one tries to do so

                                                                                                                                                              – Varshaan
                                                                                                                                                              Oct 28 '16 at 15:43
















                                                                                                                                                            0














                                                                                                                                                            if ( ! defined('BASEPATH')) exit('No direct script access allowed');


                                                                                                                                                            will do the job smooth






                                                                                                                                                            share|improve this answer



















                                                                                                                                                            • 2





                                                                                                                                                              Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                                                                                                                                              – jimasun
                                                                                                                                                              Oct 28 '16 at 15:37













                                                                                                                                                            • i know there is no need but if any one tries to do so

                                                                                                                                                              – Varshaan
                                                                                                                                                              Oct 28 '16 at 15:43














                                                                                                                                                            0












                                                                                                                                                            0








                                                                                                                                                            0







                                                                                                                                                            if ( ! defined('BASEPATH')) exit('No direct script access allowed');


                                                                                                                                                            will do the job smooth






                                                                                                                                                            share|improve this answer













                                                                                                                                                            if ( ! defined('BASEPATH')) exit('No direct script access allowed');


                                                                                                                                                            will do the job smooth







                                                                                                                                                            share|improve this answer












                                                                                                                                                            share|improve this answer



                                                                                                                                                            share|improve this answer










                                                                                                                                                            answered Oct 16 '15 at 12:38









                                                                                                                                                            VarshaanVarshaan

                                                                                                                                                            346718




                                                                                                                                                            346718








                                                                                                                                                            • 2





                                                                                                                                                              Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                                                                                                                                              – jimasun
                                                                                                                                                              Oct 28 '16 at 15:37













                                                                                                                                                            • i know there is no need but if any one tries to do so

                                                                                                                                                              – Varshaan
                                                                                                                                                              Oct 28 '16 at 15:43














                                                                                                                                                            • 2





                                                                                                                                                              Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                                                                                                                                              – jimasun
                                                                                                                                                              Oct 28 '16 at 15:37













                                                                                                                                                            • i know there is no need but if any one tries to do so

                                                                                                                                                              – Varshaan
                                                                                                                                                              Oct 28 '16 at 15:43








                                                                                                                                                            2




                                                                                                                                                            2





                                                                                                                                                            Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                                                                                                                                            – jimasun
                                                                                                                                                            Oct 28 '16 at 15:37







                                                                                                                                                            Copy paste from CodeIgnitor. That's cool but it actually doesn't do anything on it's own. The BASEPATH const is set in a index.php file that lays at the bottom of the tree structure. CI rewrites the URLs so there is no need for accessing the scripts directly anyways.

                                                                                                                                                            – jimasun
                                                                                                                                                            Oct 28 '16 at 15:37















                                                                                                                                                            i know there is no need but if any one tries to do so

                                                                                                                                                            – Varshaan
                                                                                                                                                            Oct 28 '16 at 15:43





                                                                                                                                                            i know there is no need but if any one tries to do so

                                                                                                                                                            – Varshaan
                                                                                                                                                            Oct 28 '16 at 15:43











                                                                                                                                                            0














                                                                                                                                                            You can use phpMyAdmin Style:



                                                                                                                                                            /**
                                                                                                                                                            * block attempts to directly run this script
                                                                                                                                                            */
                                                                                                                                                            if (getcwd() == dirname(__FILE__)) {
                                                                                                                                                            die('Attack stopped');
                                                                                                                                                            }





                                                                                                                                                            share|improve this answer




























                                                                                                                                                              0














                                                                                                                                                              You can use phpMyAdmin Style:



                                                                                                                                                              /**
                                                                                                                                                              * block attempts to directly run this script
                                                                                                                                                              */
                                                                                                                                                              if (getcwd() == dirname(__FILE__)) {
                                                                                                                                                              die('Attack stopped');
                                                                                                                                                              }





                                                                                                                                                              share|improve this answer


























                                                                                                                                                                0












                                                                                                                                                                0








                                                                                                                                                                0







                                                                                                                                                                You can use phpMyAdmin Style:



                                                                                                                                                                /**
                                                                                                                                                                * block attempts to directly run this script
                                                                                                                                                                */
                                                                                                                                                                if (getcwd() == dirname(__FILE__)) {
                                                                                                                                                                die('Attack stopped');
                                                                                                                                                                }





                                                                                                                                                                share|improve this answer













                                                                                                                                                                You can use phpMyAdmin Style:



                                                                                                                                                                /**
                                                                                                                                                                * block attempts to directly run this script
                                                                                                                                                                */
                                                                                                                                                                if (getcwd() == dirname(__FILE__)) {
                                                                                                                                                                die('Attack stopped');
                                                                                                                                                                }






                                                                                                                                                                share|improve this answer












                                                                                                                                                                share|improve this answer



                                                                                                                                                                share|improve this answer










                                                                                                                                                                answered Jan 31 '17 at 8:23









                                                                                                                                                                namconamco

                                                                                                                                                                2,372104574




                                                                                                                                                                2,372104574























                                                                                                                                                                    0














                                                                                                                                                                    this is what google uses in their php examples see here



                                                                                                                                                                    if (php_sapi_name() != 'cli') {
                                                                                                                                                                    throw new Exception('This application must be run on the command line.');
                                                                                                                                                                    }





                                                                                                                                                                    share|improve this answer




























                                                                                                                                                                      0














                                                                                                                                                                      this is what google uses in their php examples see here



                                                                                                                                                                      if (php_sapi_name() != 'cli') {
                                                                                                                                                                      throw new Exception('This application must be run on the command line.');
                                                                                                                                                                      }





                                                                                                                                                                      share|improve this answer


























                                                                                                                                                                        0












                                                                                                                                                                        0








                                                                                                                                                                        0







                                                                                                                                                                        this is what google uses in their php examples see here



                                                                                                                                                                        if (php_sapi_name() != 'cli') {
                                                                                                                                                                        throw new Exception('This application must be run on the command line.');
                                                                                                                                                                        }





                                                                                                                                                                        share|improve this answer













                                                                                                                                                                        this is what google uses in their php examples see here



                                                                                                                                                                        if (php_sapi_name() != 'cli') {
                                                                                                                                                                        throw new Exception('This application must be run on the command line.');
                                                                                                                                                                        }






                                                                                                                                                                        share|improve this answer












                                                                                                                                                                        share|improve this answer



                                                                                                                                                                        share|improve this answer










                                                                                                                                                                        answered Jan 17 at 22:01









                                                                                                                                                                        ToskanToskan

                                                                                                                                                                        5,306754101




                                                                                                                                                                        5,306754101






















                                                                                                                                                                            1 2
                                                                                                                                                                            next




                                                                                                                                                                            protected by Taryn Jul 21 '17 at 16:57



                                                                                                                                                                            Thank you for your interest in this question.
                                                                                                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                                                                                                            Popular posts from this blog

                                                                                                                                                                            Monofisismo

                                                                                                                                                                            Angular Downloading a file using contenturl with Basic Authentication

                                                                                                                                                                            Olmecas