Password Protect With Cookies


This tutorial is based of kane0ner's Password Protect Tutorial which can be found at https://tutorial.ninja/tutorials/Web+Development/PHP/47/Password+Protect.html

The code is the same but i've added COOKIES to keep you logged in.

PHP Code
  1. <?php
  2. ob_start(); //start output buffer, allow cookies
  3. $user = "USERNAME"; //Username to protected page
  4. $pass = "PASSWORD"; //Password to protected page
  5.  
  6.  
  7. if((isset($_POST['login']) && $_POST['username'] == $user && $_POST['password'] == $pass) || (isset($_COOKIE['username']) && $_COOKIE['username'] == $user && $_COOKIE['password'] == $pass)) { // If you entered the username/password correctly
  8.  
  9. echo "Top secret hidden content here!"; // Change content here
  10.  
  11. if(isset($_POST['login'])) {
  12. setcookie("username", $_POST['username'],time()+(60*60*24*5), "/", ""); //set the username cookie
  13. setcookie("password", $_POST['password'],time()+(60*60*24*5), "/", ""); //set the password cookie
  14. }
  15.  
  16. } else if(isset($_POST['login'])) { // If you didn't enter it correctly
  17. echo ('Incorrect username/password!');
  18. }
  19.  
  20. if(!isset($_POST['login']) && !isset($_COOKIE['username'])) { // If you didn't log in it will show the login screen
  21. echo ('<form method="POST">
  22. <table>
  23. <tr><td>Username:</td><td><input type="text" name="username"></td></tr>
  24. <tr><td>Password:</td><td><input type="password" name="password"></td></tr>
  25. <tr><td><input type="submit" name="login" value="Log In"></td></tr>
  26. </table>
  27. </form>');
  28. }
  29.  
  30. ?>


Enjoy! feel free to post bugs/questions/comments
chrism's Avatar
Author:
Views:
2,155
Rating:
Posted on Saturday 21st December 2024 at 07:26 PM
DanielXP
DanielXP's Avatar
I've updated the code for this and the tutorial it is based on
Posted on Wednesday 7th March 2007 at 08:51 PM
ShadowMage
ShadowMage's Avatar
i did one with sessions lol
Posted on Wednesday 7th March 2007 at 08:48 PM
MOD-Dan
MOD-Dan's Avatar
Also this would work with the techtuts user system we are using sessions here not cookies! Recoding needed!
Posted on Wednesday 7th March 2007 at 08:09 PM
ShadowMage
ShadowMage's Avatar
its echoing the bottom line anyway when i look at it o.o i'll post a simple session one here in a bit =P
Posted on Wednesday 7th March 2007 at 07:58 PM
paradox
paradox's Avatar
no becuase theres nothing connection to the database and it uses its own cookie
Posted on Wednesday 7th March 2007 at 04:30 PM
ashwill
ashwill's Avatar
Dont you need to include config?
Posted on Wednesday 7th March 2007 at 05:59 AM
FtH8er
FtH8er's Avatar
Well mine comes up on the page but doesnt go anywhere lol. When i say this i mean, when i enter the info into the boxes, and login, it acts like it is gonna process it, but then it just reloads the page. Plz Help. Thx