Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP password protected page cookie

I have a very simple PHP password protected page. I'd like to add a session cookie so the browser will stay logged (say for 7 days).

Here is my current code:

<?php

$password = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";

if (sha1($_POST['password']) == $password) {
?>

Password Protected Content

<?php

}

else {

?>
<html>
    <head>
        <title>Login Page</title>
    </head>
    <body>
        <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        Password: <input type="password" name="password" class="formpart" />
        <input type="submit" name="Submit" value="Login" class="login-button" />
        </form>
    </body>
</html>
<?php
}
?>

I have no idea where to start, so I'd really appreciate some help. Thanks in advance!

like image 973
Harold Dunn Avatar asked Oct 15 '25 03:10

Harold Dunn


2 Answers

Please make yourself a look on this things for PHP:

  • session_start()
    • Next take a look here: How to change the session timeout in PHP?
  • $_SESSION[]-Array

Also your code will never jump into the password protected content block.

$password = "password";

if (sha1($_POST['password']) == $password) {

Let's say you gave in the right password ("password") - so the if would ask:

if 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 equals password.

You are using hashing, but that is not needed here.

like image 104
Dennis Ziolkowski Avatar answered Oct 17 '25 16:10

Dennis Ziolkowski


Your requirement is a very classical practice. You can read a tutorial here: http://www.phpnerds.com/article/using-cookies-in-php/2

Notes:

  • Compare hash to hash
  • Never save your plain-text password in a cookie
  • More secure: don't save hashed passwords in cookies like the tutorial. Just store a session hashed code and using a DB table session to map it with the user's sessions.

Hope it helps.

like image 33
Tu Hoang Avatar answered Oct 17 '25 16:10

Tu Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!