Log in

View Full Version : Login Script Using Cookies



smithster
05-18-2008, 10:57 AM
I've got here a very basic login script which is supposed to create a cookie. I'm having a few problems with it though. Here's what I've got...

Login.php


<?php

if(isset($_COOKIE['username']) || $_COOKIE['password']){
$username = $_COOKIE['username'];
$password = $_COOKIE['password'];
if ($username == "test" && $password == "test"){
echo 'cookie logged in<br />';
echo 'Click <a href="logout.php">here</a> to log out';
}
}

if(isset($_POST['submit'])){

$username = $_POST['username'];
$password = $_POST['password'];

if ($username == "test" && $password == "test"){
setcookie("username", $username, time()+3600, "/");
setcookie("password", $password, time()+3600, "/");
echo 'logged in<br />';
echo 'Click <a href="logout.php">here</a> to log out';
}
else {
echo 'Log in failed';
}
}
else {
if(!isset($_COOKIE['username'])){
echo '<form action="" method="POST">';
echo 'Username - <input name="username" type="text"><br />';
echo 'Password - <input name="password" type="password"><br />';
echo '<input name="submit" type="submit" value="Submit"><br />';
echo '</form>';
}
}
?>


Logout.php


<?php
setcookie("username", "", time()-60);
setcookie("password", "", time()-60);
header("Location: login.php");
?>

I want to solve one problem at a time so here's the first one...

The login script works. A cookie is created and lasts for one hour. I can login in, close the page, go back to it and still be logged in for up to an hour from being inactive. If I try to log out myself, it doesn't seem to work. It takes me back to the login.php page where it asks me to log in again but if I close the page and reopen it, I'm still logged in. So for some reason the cookie still exists.

Any ideas what's wrong with it?!?!?

Thanks in advance.

thetestingsite
05-18-2008, 02:43 PM
Logout.php:



<?php
setcookie('username', '', time()-3600, '/');
setcookie('password', '', time()-3600, '/');
header("Location: login.php");
?>


The above code now works with your login script above.
Hope this helps.