1

On my login system, I have it pop up in a fancyBox lightbox requested via AJAX. But there's one problem. If the user goes to login.php itself in their browser, they see an unstyled page that doesn't work because the JavaScript that helps it is on the page that has the login pop up. I want to redirect them to the homepage if they are on login.php.

I tried doing this:

<?php
if($_SERVER['REQUEST_URI'] == '/login.php') {
header("Location: /");
}
?>

As well as:

<?php
if($_SERVER['PHP_SELF'] == '/login.php') {
header("Location: /");
}
?>

Which both do not work because when you open up the fancyBox it messes up the page and makes it blank.

Is there a way to make it redirect if the user is at the login page itself that doesn't affect the fancyBox?

Nathan
  • 11,814
  • 11
  • 50
  • 93

2 Answers2

2

Put this in your login.php script to detect non ajax requests and redirect in that case:

//Redirect the user if page not requested via ajax
if(!$_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { header('Location: /'); }
Calvin Froedge
  • 16,135
  • 16
  • 55
  • 61
  • While most of the major frameworks do pass in the X_REQUESTED_WITH flag with requests, this is only reliable assuming that the user is using a framework. Passing a POST or GET variable is more reliable in a Framework-agnostic way. – Brendon Dugan Dec 29 '11 at 18:29
  • 2
    Ah, my bad. I'm used to working with $_SERVER as $this->server = ). Updated to use $_SERVER['HTTP_X_REQUESTED_WITH'] – Calvin Froedge Dec 29 '11 at 18:29
  • @Nathan, if you replace $this->server with $_SERVER you may have better luck, but you will still have the same pitfall as I described in my last comment. – Brendon Dugan Dec 29 '11 at 18:31
  • On Brendon's useful, valid point, this is a helpful post: http://stackoverflow.com/questions/2579254/php-does-serverhttp-x-requested-with-exist-or-not – Calvin Froedge Dec 29 '11 at 18:32
  • jQuery should send the flag, yes. – Brendon Dugan Dec 29 '11 at 18:33
  • @BrendonDugan - so I can use this with jQuery and not have that problem that you were saying in your first comment? – Nathan Dec 29 '11 at 18:37
1

I would suggest passing in a post or get variable in your ajax call that indicates to the script that the request is from ajax. Something like:

if(isset($_REQUEST["yay_ajax"])){
    // Output your login stuff
}
else{
    header("Location: index.php");
}
Brendon Dugan
  • 2,138
  • 7
  • 31
  • 65