0

In every PHP file in my project I am using the following code so that nobody can get into the website without logging in:

<?php
    session_start();
    if($_SESSION['userid']!="myuserid"){
        header("Location: Adminlogon.php");
    }
?>

Note that I need only one user id, the user id and password is shared among a group of people.

Is this code safe? Can I do better?

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • 8
    Put `exit()` after you send your redirect header. – John Conde Apr 26 '12 at 17:41
  • It's not bullet-proof (few things are), but it will do well enough for a simple deterrent. – Blake Apr 26 '12 at 17:42
  • If you're looking for security then I'm not sure a shared id/password is a great way to go, unless you're enforcing only one sign-on at a time (i.e. if someone else tries to sign on you deny it as long as there's a session active). If not then what's to stop people for sharing the id/password with other (unauthorized) users? – TheOx Apr 26 '12 at 17:51

2 Answers2

0

That will be safe, but cookie and session can be easily "hijacked" in LAN when you are using plain HTTP. So force your application server to use HTTPS

Superbiji
  • 1,723
  • 2
  • 14
  • 21
0

Your code is not safe, because actually it does not prevent from each script being executed - which is what you actually want to prevent.

To prevent execution if the session is not set correctly, you need to leave the file, for example with the return statement:

<?php
    session_start();
    if ($_SESSION['userid'] != "myuserid")
    {
        header("Location: Adminlogon.php");
        return; ### leave this script/include
    }
?>

Instead of return you can also use the exit or die statement for rudimentary scripts.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • If your program has any registered shutdown functions or object destructors, they will still run even after the exit statement. – Dmitri Snytkine Apr 26 '12 at 19:03
  • @DmitriSnytkine: And if you've got a serialized payload inside the session, it will exploit the application as well. – hakre Apr 26 '12 at 20:16