阻止访问使用AJAX的php脚本
I made a script that is being used by only AJAX calls(checks for user and password and logs the user in). The problem comes when I want to prevent the user from accessing the script directly through his browser like mywebsite.com/login.php
.
If I do something like
if ( isset( $_SESSION['id'] ) ) header( "Location: logged.php" );
else header( "Location: index.php" );
where logged.php
is for logged in users, this will execute when the AJAX calls are done, as well, so it will redirect to index when the AJAX call is made. If I remove the 'else' part, they can access it directly.
我制作了一个仅由AJAX调用使用的脚本(检查用户和密码并记录用户) 。 当我想阻止用户通过他的浏览器直接访问脚本时,问题就出现了,如 如果我这样做的话 p>
其中 mywebsite.com/login.php code>。 p>
if(isset($ _SESSION ['id']))header(“Location:logged.php”);
else header(“Location:index.php”) ;
code> pre>
logged.php code>用于登录用户,这将在AJAX调用完成时执行,因此它 在进行AJAX调用时,它将重定向到索引。 如果我删除'else'部分,他们可以直接访问它。 p>
div>
If I understand your question correctly you could add an extra POST var to your Ajax Call and do something like this
if( $_POST["call"] == true ){
//do ajax stuff
}else{
if( isset( $_SESSION['id'] ) ){
header( "Location: logged.php" );
}else{
header( "Location: index.php" );
}
}
Check the Request HEADER
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
} else {
// NO AJAX CALL
// die("NOT ALLOWED") ... or what ever
}