`

How to create a PHP login form

A quick tutorial on creating a basic PHP login form.

Create a new php file, we will call this one login.php for the tutorial.
In login.php we need to add a form for the user to enter their credentials:

<form action="login_check.php" method="post">
<label>User Name
<input type="text" name="user" />
<label>Password
<input type="password" name="pass" /><br />
<button type="submit" name="submit">Sign in
</form>

Now we create login_check.php. In there we put the following code:

<?php
// Set the username and password here
$user = "username";
$pass = "password";
if ($_POST['user']==$user && $_POST['pass']==$pass){
$pass_secure = md5($pass); // Add md5 encryption to the password
$expire=time()+60*60*24*30; //Set the expiration of the cookie
setcookie("username", $user, $expire); // Add a cookie called "username"
setcookie ("password", $pass_secure, $expire); //Add a cookie called "password"
header('Location: whatever_page_you_want.php');
}
else {
echo "Incorrect username/password";
}
}
?>

Effectively, the code above checks the username and password, if they match then it sets a cookie for the username and password.

Now if you add this code to the top of every page you want protected by the login script then if these cookies are not set, it will redirect you back to the login page:
<?php
if(!$_COOKIE['username'] || !$_COOKIE['pass']){
header('Location: login.php');
}
?>

Pretty simple eh? This form is by no means secure as it stores the login data using cookies. Even thought the password has been encrypted using md5, it can still be decoded! You have been warned!

Posted on
Saturday, November 14th, 2009
Filed under:
Geekery
Tutorials.
Tags:

Subscribe
Follow responses trough RSS 2.0 feed.
Trackback this entry from your own site.

2 Comments to “How to create a PHP login form”

Good catch Robert, thanks for that. Next will be a tutorial on a secure login form I think outlining salting passwords and using sessions.

November 14th, 2009
Darren

Aloha :)

The if($_POST… line should contain the “and” operator instead of the “or”. You want to check that both of them are correct, not just one :)

November 14th, 2009
Robert
The Pointing Cow is proudly powered by WordPress
Revolt Basic theme by NenadK. | Entries (RSS) and Comments (RSS).