Simple PHP login with cookie
Please don't try to store things like "authenticated" in a client side cookie; that's incredibly insecure. A user can modify anything in a cookie - so in this case, I could look up the cookie in my browser settings and then edit it to set "authenticated" to true. I would then be logged in, without a username or password.
Have a look at PHP's session management functions. You should create a session and store any secure information server side, not client side.
An example using sessions would be the following;
<?php
session_start();
$secretpassword = 'qwert1234';
$secretusername = 'foobar';
if ($_SESSION['authenticated'] == true) {
// Go somewhere secure
header('Location: secure.php');
} else {
$error = null;
if (!empty($_POST)) {
$username = empty($_POST['username']) ? null : $_POST['username'];
$password = empty($_POST['password']) ? null : $_POST['password'];
if ($username == $secretusername && $password == $secretpassword) {
$_SESSION['authenticated'] = true;
// Redirect to your secure location
header('Location: secure.php');
return;
} else {
$error = 'Incorrect username or password';
}
}
// Create a login form or something
echo $error;
?>
<form action="login.php"><input type="text" name="username" /><input type="text" name="password" /><input type="submit" value="login" /></form>
<?php
}
It's a pretty ugly example, but this covers the meat of it
- if the user is logged in already, do the secure stuff (of course, the secure.php script should also verify that the user is logged in)
- if the user is not logged in, but they have submitted a form, check their details
- if username/password incorrect, set an error messagee
- if username/password correct, send them to secure place
- display the error message, if set
- display a login form
You run session_start() before sending any other output; this stores a session cookie on the client side, which only stores an identification number on the client side. All other data is stored on the server side, so it cannot be modified by the user.
There are several parameters that you can set on this to improve security, including httponly (prevents the cookie from being accessed via javascript, helps against XSS attacks) and secure (only transfer the cookie over SSL). These should be enabled if possible.
PHP login session and cookie
It seems that you don't have a clear vision of sessions and cookies!
No body can change the session contents except your code (beside attacks). So you can store everything (reasonable) like user id
or username
that you need to access frequently. in cookies you must store some obfuscated information that you can recognize user later when he/she tries to access your page. so based on cookie content you can regenerate users session (ie. re-login user automatically). Just to note that user CAN change cookies content so it must not be something simple like user id
for security reason.
I just give you a simple example, it's far from perfect but not so bad! you may need to tailor it to fit your scenario:
here you can create cookie content like this:
$salt = substr (md5($password), 0, 2);
$cookie = base64_encode ("$username:" . md5 ($password, $salt));
setcookie ('my-secret-cookie', $cookie);
and later to re-login user you do:
$cookie = $_COOKIE['my-secret-cookie'];
$content = base64_decode ($cookie);
list($username, $hashed_password) = explode (':', $hash);
// here you need to fetch real password from database based on username. ($password)
if (md5($password, substr(md5($password), 0, 2)) == $hashed_password) {
// you can consider use as logged in
// do whatever you want :)
}
UPDATE:
I wrote this article that covers this concept. Hope it helps.
PHP Cookie Login System
you have an error in the login script.
if(!$_POST['username'] | !$_POST['password']) {
die('You did not fill in a required field.');
}
and it should be
if(!$_POST['username'] || !$_POST['password']) {
die('You did not fill in a required field.');
}
Also you are not storing the cookie in your login page.
Look out for the comment
// if login is ok then we add a cookie
You have not added the cookie there. Below is the way to add cookie.
setcookie("TestCookie", $value);
Below is the way to set cookie with time.
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
And below is the way to retrieve cookie.
echo $_COOKIE["TestCookie"];
PHP: User logged in sessions and cookies
First off, there is an important difference between a session and a cookie. When you use the $_SESSION[".."]
you are creating a session (which lives on the server, compared to a cookie which lives on the client), even though the browser uses a cookie to keep track of the session id. To create a cookie you would use the setcookie() method.
That said, I would recommend you to read through this article which is a step-by-step guide on how to create a secure login script, with persistence using a cookie for a "Remember me"-feature. Describe how to do it in detail would be to extensive for an SO answer im afraid.
Side note:
To be able to write to the session, you might have to call session_start();
prior to getting or setting a session variable using $_SESSION[".."]
.
Are cookies necessary for a login page?
Answer simply is yes.
Sessions rely on a session id.
Sessions in php use a cookie to store this id, but you can change it to append the id to each url instead of saving it in cookies.
ini_set('session.use_cookies', false);
in the config variable url_rewriter.tags
, you see which URLs automatically get rewritten to append this id:
"a=href,area=href,frame=src,form=,fieldset="
As Pekka mentions, jQuery requests and special JS/Ajax/jQuery calls are not getting rewritten by default and you have to append the id manually like:
<script>
$.get('/yourpage/?PHPSESSID=<?php echo session_id(); ?>');
</script>
the session name can be obtained via session_name();
, default is in the config variable: session.name
.
Use ini_get();
or phpinfo();
to see your configuration.
Set a cookie to save login details PHP
First of all: do not save passwords in a cookie! This is a very bad idea security-wise.
As for your problem: there is no way around it, you need to have no output at all before setting your cookie. There are two ways to achieve this:
Solution 1: the login page always redirects
Have your login requests go to a script which sets a cookie (if the login was successful) and then always redirects the user to another page (e.g. a welcome screen, or back to the login page if unsuccessful). The login script will not emit any output, therefore you can set cookies before redirecting.
Solution 2: output buffering
Start output buffering at the beginning of your script. After the check for successful login, set the cookie first and then stop output buffering with something like ob_end_flush
.
Personally I consider solution #1 to be more elegant and superior in function.
Related Topics
Using Xampp, How to Swap Out PHP 5.3 for PHP 5.2
Stemming Algorithm That Produces Real Words
Storage in Laravel Says Symlink - No Such File
How Is Annotation Useful in PHP
Fatal Error - Too Many Open Files
Send Email with a Template Using PHP
Check If String Is Just White Space
How to Block 100,000+ Individual Ip Addresses
Windows 7 PHP + Symfony2 Terribly Slow
How to Load a PHP File into a Variable
PHP How to Go One Level Up on Dirname(_File_)
What Is the Best Method to Prevent a Brute Force Attack
Zip All Files in Directory and Download Generated .Zip