How to determine if a file is accessed or requested?

A I have a PHP file which, if the user accesses it directly, should be redirected to another place, but if my script calls it via ajax, it should not do anything special.

For example, if the user has access to

/site/page.php 

it should be redirected to

 /index.php?view=page 

But if it is in index.php?view=page , the file should be loaded without redirection.

How can i do this?

0
jquery ajax php
source share
3 answers

EDIT . If you want to determine whether a script was requested through Javascript or not, you will have to notify it somehow.

Several toolkits define the X-Requested-With header. In this case, you can check the Javascript call with:

 if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { //requested with Javascript } 

You can check the size of the result given by debug_backtrace .

Alternatively (better) you can check $_SERVER['SCRIPT_FILENAME'] :

 if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) { //this one was requested; not in include } 

+5
source share

By "nothing should do anything special," do you mean that it should not be redirected?

So, Q really, if the user accesses the URL for the PHP file directly, should he redirect if it is processed as usual through AJAX? (to really clarify, you mean through the url, not through the include statement?)

Answer: You cannot. Artefacto mentions the HTTP_X_REQUESTED_WITH header - required, but it can be faked.

Is it really so bad that the user directly accesses the URL? If the answer is "OMG Yes!" then maybe something is wrong with how the system is designed. Redesign it until it replies, "In fact, I suppose it won't hurt."

0
source share

If you really do not want someone /site/page.php , you should consider moving /site/page.php outside of your web root. Then make your index.php load as needed:

 <?php $includes = "/path/to/includes"; // specified in a config file somewhere if ($_GET["view"] == "page") { require_once(path_join($includes, "page.php")); DoStuffInPageDotPHP(); } else { DoSomethingElse(); } ?> 
0
source share

All Articles