0

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.

2
  • So what is the problem with this code? Commented Oct 20, 2014 at 10:12
  • When the user logs in through my html form, it will set the ssid, but will redirect him back to index.php instead of logging him in. He will need to refresh the page for logged.php to work. Commented Oct 20, 2014 at 10:14

2 Answers 2

1

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" );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't ($_SERVER['REQUEST_METHOD']) == 'POST' be ok, too? So I don't add an extra variable? Or can users bypass this, too?
1

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.