tags:

views:

45

answers:

3

A I have a PHP file that if the user access it directly he should be redirected to another location, but if my script call it through ajax, it should do nothing special.

For example, if a user access

/site/page.php

he should be redirected to

/index.php?view=page

But if he is on the index.php?view=page the file should load without redirects.

How can I do that?

+3  A: 
Artefacto
I don't think this is what the OP means. (Although I'm not sure *what* the OP means.)
Pekka
Both accessing the page and making a call returned true on your second answer.
BrunoLM
@Pekka Well, I just read the title :p
Artefacto
`debug_backtrace` returned an empty array.
BrunoLM
@Bruno I've edit my answer, but I'm still not sure if this is what you want. Perhaps you should write a clearer question.
Artefacto
A: 

By "it should do nothing special" do you mean it shouldn't redirect?

So the Q is really if user accesses a URL for a PHP file directly, it should redirect, if thru AJAX, process as normal? (to really clarify, you mean thru a URL and not thru a include statement, right?)

Answer: You can't. Artefacto mentions the HTTP_X_REQUESTED_WITH header - sure, but that can be faked.

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

James
In this case it doesn't matter if it can be faked. And it is important that the page redirect because search engines wouldn't work properly for this application.
BrunoLM
Search engines? I don't understand. You don't want this page to appear in search engines? If this page is linked only from Javascript AJAX calls then a search engine bot will never find it and will never visit it. IF you are really paranoid that the link will leak out, put a X-Robots-Tag http header on it. http://googleblog.blogspot.com/2007/07/robots-exclusion-protocol-now-with-even.html
James
A: 

If you really don't want someone accessing /site/page.php, you should consider moving /site/page.php outside of your web root. Then make your index.php load it 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();
}
?>
Seth