views:

43

answers:

2

Hello all..

I have this problem with my code, the page is redirecting and wouldn't stop.. The browser stop it because it's redirecting all the time, and I have a global.php file that included in all php pages, so I putted this code for the session and it went like what I said

if (!session_is_registered('username')) {
    if(!eregi('login.php', $PHP_SELF)) header('Location: login.php');
}

Also global.php included in login.php, but when I start it on the web server of my site, it does what i said before, but on my based server on computer it works fine, so please help me fast

and sorry for my english..

A: 

Try:

if (!isset($_SESSION('username'))) {
    if(FALSE === strpos($_SERVER['PHP_SELF'], 'login.php')) {
      header('Location: login.php');
      exit();
    }
}

Some Suggestions:

  • Make sure that you have session_start() placed on top of your script
  • Use isset($_SESSION.......
  • Use strpos instead of deprecated eregi
  • Don't use deprecated session_is_registered
  • Use exit/die after header redirect
  • It is $_SERVER['PHP_SELF'] not $PHP_SELF
  • Use error handling, put these lines on top of your script:

    • ini_set('display_errors', true);
    • error_reporting(E_ALL);
Sarfraz
`display_errors` shouldn't be hardcoded to true. Set it using `php.ini` so you can easily change it when you move between production and development environments.
Daniel Egeberg
@Daniel EgebergL It is to be there for testing his current script :)
Sarfraz
thank you too :)
phplover
+2  A: 

Try this:

session_start();
if (!isset($_SESSION['username']) && stripos($_SERVER['PHP_SELF'], 'login.php') === false) {
    header('Location: login.php');
}

Both session_is_registered() and eregi() are deprecated functions and shouldn't be used. Plus, regular expressions are overkill for what you're doing anyways.

Daniel Egeberg
Since OP is using `eregi`, probably `stripos` should be used instead of `strpos`.
KennyTM
@KennyTM: Good point. Updated now.
Daniel Egeberg
Thanks mate very much .. this worked fine
phplover