开发者

PHP & jQuery .load() - If you visit the .load() URL, redirect back

I am using jQuery load, to load some data from an external file like this:

$("#div1").load("test.php");

Now this works fine but I want users not to be able to visit test.php. In case they type in the URL test.php, get redirected to index.php

I tried this:

I inserted in my index: <? $fromIndex = true; ?> and this in my test.php file:

<? 
$fromIndex = true;
if(!isset($fromIndex) || !$fromIndex) {
    header("Location: index.php");
    exit();
}
 ?>

The re开发者_JS百科direction works great if you visit test.php but the load doesn't work from index.php.

EDIT: Note: I wouldn't mind changing the test.php to .xml ? Or anything else that would help. The content I'm loading is few <option>'s

Can someone help me please?

Thanks alot


There's not really a way for you to prevent a user visiting a URL directly, and yet still allow AJAX access to that same URL. A simple way to dissuade them, though, would be to either A) send the response back as a JSON object (which makes it pretty useless when accessed directly), or B) append a GET parameter to the URL and perform your redirect when that parameter is absent.

$("#div1").load("test.php?ajax=1");

and

<? 
if( !isset( $_GET['ajax'] ) || $_GET['ajax']!=1 ) {
    header( "Location: index.php" );
    exit();
}
?>


jQuery's AJAX functions all send a X-Requested-With header with the contents XMLHttpRequest. You can use this to do what you want, but don't use it as an anti-abuse feature - it's trivially defeated. It should only be used to be helpful to users who stumble across the URL, or to present them with a helpful error page instead of say, a JSON feed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜