Simple PHP Login or Signin Script

This tutorial aims to present/show a simple 'log in' or 'sign in' script written in PHP, which you can use on your websites with little modifications. Script is tested before publishing and successfully executed without any error. So, here we go, You need to create two pages on your site with one having a form and other with PHP script. First of all, we will create a simple login form. Paste this code on any web page which you'll like to use for login purpose.

See the code below:

<!-- the " name="" " attrbute used here is mandatory, which have its use in php script --> 
<form method="POST" action="link of page that have php script" >
<input type="text" name="username" /> 
<input type="text" name="password" /> 
<input type="submit" value="Log In" />
</form>

Now, We'll write our php script which will do the authentication work using the values submitted by login form. We first need to create a table in our site database with table-name 'login' having this attributes "id (auto increment)", "username", "password". if you didn't created your Site database, Then, go to control panel of your host and create one with your site's name.


(*)Tips:

  1. Create a separate page for this php script.
  2. Sql injection (mysql_real_escape_string() function) is used for security purposes such as protecting our script and sensible data from hackers - You can read the whole article about sql injection here.
  3. The lines with green color in the code below are comments and does not play any role in authentication, they are used to understand code better.
  4. This is not the advanced version of 'login script' but it's the base on which, you can also try your ideas to enhance it such as making more secure and multifunctional.

<?php 
	/* $con make a connection with database */
$con=mysql_connect("hostname","username","password"); 

	//select  database
mysql_select_db("database name"); 

/* Below two commands will store the data in variables came from form input */
$username=$_POST['username'];
$password=$_POST['password'];

/* below two commands are sql injection which stops extra characters as input */
$user=mysql_real_escape_string($username);
$pass=mysql_real_escape_string($password);

$query=mysql_query("SELECT * FROM login where
username='$user' AND 
password='$pass' "); 

$count=mysql_num_rows($query);
if($count==1) 
	/* $count checks if username and password are in same row */
{ 
 echo "Login Successful";
 $hour = time() + 3600;  
	/* $hour sets cookie storage time for 1 hour */

	/* setcookie() function sets cookie after login */
 setcookie("username", $username, $hour); 
 setcookie("password", $password, $hour);

 header("location: redirecting page link"); 
	/* header() function redirect user to members page */
}
else
{ 
echo "Username or password is incorrect";
}
?>

Now, to check if user is already logged in, We use $_COOKIE['username'] for the purposes like redirecting, displaying login or logout at user screen.

see example below:

<?php
/* 
You should make changes in if else loops according to your needs here */

if(isset($_COOKIE['username']))
{
echo "You were already logged in ".$_COOKIE['username'].".";
/* " $_COOKIE['username'] " will fetch the username from cookie stored on browser if user is already looged on */

include("template_file_address");
//or you can redirect it to another page....
}
else 
{
header("location: login.php");
}
?>

Well, We already set the time of 1 hour in cookie itself for expiring but if user wants to 'Log Out' or 'Sign Out' from site earlier then here is the Logout script below. Create a new page with name 'logout.php' and paste this script in it with little modification in 'header()' function and paste the link of 'logout page' in your template or on every page that required login.

 <?php 
 /* we are setting the time of cookie destruction in the past to destroy the cookie */
 $past = time() - 100; 
 setcookie("username", gone, $past); 
 setcookie("password", gone, $past); 
 header("Location: link of login page or thank u page"); 
 ?> 

Hope, this article is easy to understand and helpful,
Thanks for your visit,
Shrikrishna Meena (An IT Student).

More by this Author


Comments 71 comments

unknown 6 years ago

Opps...SQL Injection...


itech profile image

itech 6 years ago from New Delhi, India Author

Thanks for introducing about 'sql injection' but I've skipped that part because to make this script simple. Well, I think I should add that part also.


unknown 6 years ago

I see.

But It's necessary to a minimum.

Otherwise this script is with a friend of PHP sucks.

(http://www.google.com/search?hl=en&source=hp&q=php...


jessicababel profile image

jessicababel 6 years ago from Portland

mysql_real_escape_string() should take care of most SQL injection issues. Looks like you already fixed it.


tammyfrost profile image

tammyfrost 6 years ago from Oregon

Another wonderful hub...Thanks.


deutsched profile image

deutsched 6 years ago from Egypt

That was extremely useful!

I'm trying to create an admin area for my website, so that will certainly help!

Thanks :)


itech profile image

itech 6 years ago from New Delhi, India Author

@deutsched , Glad to see that it will help you.


life.object profile image

life.object 5 years ago from Lahore, Pakistan

Nice hub, It is a useful information.

I will also recommend to add exit() code after redirect header. It will sure a save redirect without executing the next code.


weekendrockstar profile image

weekendrockstar 5 years ago from SE Pennsylvania

I have several ideas I could add to this but I will stick with one. While the use of cookies is normally fine you may want to make use of PHP SESSIONS.

If you plan on having more than just yourself login then you can run into users that have cookies turned off in their browser. The would still be able to login because of the POST data. But if cookies cannot be set and they navigate away from the page they'd have to login again.

If you create a session for each person that correctly logs in then their credentials will be good even if they navigate away from the protected page and return to it. The session info will remain on the server's memory until the browser window is closed.

But it's a good idea to use both together which you see on most sites that allow user logins...most of them have a 'keep me logged in' link which usually sets a cookie for about two weeks. This way if the logged in user can accept cookies, closes the browser window/tab with your site in it...the login routine will check to see if the cookie is set which it would be unless the time runs as specified in the cookie or is manually deleted from the user's hard drive.

Just an idea =0)


itech profile image

itech 5 years ago from New Delhi, India Author

Thanks weekendrockstar for commenting and for sharing your useful knowledge.I was just trying here to explain the mechanism of login via php, so, learners can easily understand and apply their own ideas.

PHP SESSIONS is good recommendations but I faced some no-execution type problems when I tested it on my server, So, I decided not to include them in this beginners tutorial (Well, Such cases are very rare).


Sandeep 5 years ago

how we can save logout time in database when user wish to logout and not by cookie


itech profile image

itech 5 years ago from New Delhi, India Author

In the end of this article, we are creating a file with name "logout.php" and with php code as show there... You can place a link to that file on any webpage of your site. If user wishes to logout, then, he can click on it.


Radjesh 5 years ago

Thanks for the great information.I have a few questions however ;)

- how do I change $hour login to forever?

- how do I hide the form and show the username after login?

Thanks in advance


samba 5 years ago

Hi itech, can u tell me how to modify the php script after i used the md5 function in registration script ?


sasajib 5 years ago

in setting cookie section quotation mark need,

=================================================

/* setcookie() function sets cookie after login */

setcookie(username, $_POST['username'], $hour);

setcookie(password, $_POST['password'], $hour);

==================================================

to:

==================================================

/* setcookie() function sets cookie after login */

setcookie("username", $_POST['username'], $hour);

setcookie("password", $_POST['password'], $hour);

==================================================

thanks for this really loved this tutorial...


itech profile image

itech 5 years ago from New Delhi, India Author

@sasajib, Thanks for pointing it out.... I will correct it now.


woskel 5 years ago

thank you...


Steve 5 years ago

Little type in the form above:

form metod="POST" s/b method


itech profile image

itech 5 years ago from New Delhi, India Author

Yup... It's small but a big Bug/Mistake... Very much thankful to you @steve


divya bhalodia 5 years ago

hiii

i create login log out script..

when i login , dashboard page display page of login user

now perss refresh button ...

i still not stay on this page..

give solution abot that plz


itech profile image

itech 5 years ago from New Delhi, India Author

hello @divya, You can check if user is already logged in or not via using this $_COOKIE[`username`]... As shown in code below login script in above article....

And to know the username of logged in user... You can do that via

$currentUSER=$_COOKIE['username'];

.... Now, you can use this variable to show dashboard containing information (which is fetched from MySQL after authentication) about particula username.


jeff 5 years ago

for some reason when i try to login, an error comes up saying >>

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/content/93/8371193/html/script.php on line 27

Username or password is incorrect

can anyone help me out here? it's this row, but there are no usernames or passwords on this row >

$count=mysql_num_rows($query);


itech profile image

itech 5 years ago from New Delhi, India Author

1) Read second paragraph of this article,

2) And then, Add new records in login table (Username + Password combination). OR

Read this article : http://hubpages.com/technology/Registration-script


Ovidiu 5 years ago

Hi, thank you for all your work. I studied your code and modified it a little, but I get a strange error.

This is my code:

require_once('config.php'); // here I make the connection to the database, also have the start_session function.

if(isset($_POST['username'])) $_POST['username'] = $username;

$password = $_POST['password'];

/*$username = $_POST["username"];

$password = $_POST["password"];

*/

$user=mysql_real_escape_string('username');

$pass=mysql_real_escape_string('password');

$reqSQL="SELECT * FROM 'ovidiu'.'users' WHERE

username='$user' AND

password='".md5($pass)."' ";

$result=mysql_query($reqSQL);

if(mysql_num_rows($result) == 1)

{

while($rand = mysql_fetch_array($result))

{

$_SESSION['logat'] = 'yes';

echo 'Logged in';

}

}else{

echo 'username or password incorrect';

}

The error is: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\users\validate_login.php on line 20

What does it means and how do I deal with it? Some ppl said that query didn't connect the DB, but in my registration form, I was able to register users, so I think I can succesfully connect the DB. What can it be? I'm having this problem for days now, and can't go on. Or if there is another way to check the database beside mysql_num_rows, I can addopt it.

Also, another thing, if I declare a variable username = _post['username'], i get another error saing Undefined index: username, so the if(isset) is the only way for me. Thank you and keep up the good work, hope you can reply me.


itech profile image

itech 5 years ago from New Delhi, India Author

hello @Ovidiu, there are many bugs/mistakes in your code, which are explained below.

1) Replace "if(isset($_POST['username'])) $_POST['username'] = $username;" with "if(isset($_POST['username'])){ $username=$_POST['username']; }",

2) Replace "'username'" and "'password'" in below two PHP statements with "$username" and "$password" without single and double quotes,

I)$user=mysql_real_escape_string('username');

II)$pass=mysql_real_escape_string('password');

3)remove the while loop including it's arguments, there is no need of it.


emmanuel 5 years ago

what is the "include("template_file_address");" plzzz??


itech profile image

itech 5 years ago from New Delhi, India Author

it is a method to include external file into current one. File can either be normal html file or a common theme/template file of your website.


emmanuel 5 years ago

is it optional?


itech profile image

itech 5 years ago from New Delhi, India Author

Yes, It is Optional!


arashi 5 years ago

Hey, I have a little bit of trouble using this script. One, the login form doesn't look how it should be. It's missing Username and Password title. Two, the password field, when typed in a password, shows out the characters instead of the encrypted dots/circles. Could you help me out on this? I need to fix it as soon as possible. Thanks.


itech profile image

itech 5 years ago from New Delhi, India Author

Hello @arashi, you can use table tags or css to resolve your first issue. Below is the sample usage of table tags.

<table>

<tr><td>Username: </td><td><input type="text" name="username" /></td></tr>

<tr><td>Password: </td><td><input type="password" name="password" /></td></tr>

</table>


itech profile image

itech 5 years ago from New Delhi, India Author

Your second issue can be resolved by changing "type" attribute to "password" of input tag which have it's "name" attribute password, as shown in above html code.


arashi 5 years ago

Thanks itech for replying so soon. I'll let you know if I encountered anymore errors.


arashi 5 years ago

Okay, I fixed it according to your comment. But when I tried to log in, with the correct password as the one I registered, it gave me the "Username or password is incorrect" error. Why is that? :/


itech profile image

itech 5 years ago from New Delhi, India Author

If you used "md5()" enryption function of php in registration script, then, you need to use it here also.

Below are steps of using it,

1) first, convert normal password into md5 hash (encrypted form) using md5 function,

2)then, use that encrypted form of password in sql query (Line no. 16 of first php script in this article) to check its existence in database.


madhu 5 years ago

very good idea


itech profile image

itech 5 years ago from New Delhi, India Author

@madhu, thnx for commenting.


Anas 4 years ago

i have a few issues:

is the cookie-bit code supposed to be in a separate file? if so how do i relate the login.html, login.php and this file.

if not then how does it work?


Anas 4 years ago

i think the header() function will not work if echo is used before it.


itech profile image

itech 4 years ago from New Delhi, India Author

@Anas, You can use this [Click Here: http://hubpages.com/technology/Simple-Php-Login-Sc...] code on every webpage of your site that required authentication. If user is not already logged in, then, he'll be redirected to login page (automatically). If you are still unsure about it, then, follow steps shown below.

1) first, Comment Out line number 10 where include function of PHP is used,

2) Then, Paste you HTML code there, which you'd like to display on screen, as shown below.

if(isset($_COOKIE['username']))

{

echo "You were already logged in ".$_COOKIE['username'].".";

?>

HTML Code of webpage will come here.

<?php

}

else

{

header("location: login.php");

}


itech profile image

itech 4 years ago from New Delhi, India Author

To resolve warnings such as "headers already sent", you can use this functions "ob_start()" at starting and "ob_end_flush()" at the end of script.


Anas 4 years ago

I see. seems like a good idea. i will definitely give it a try. thanks for the help. i'll ask again if theres a issue.


itech profile image

itech 4 years ago from New Delhi, India Author

You are always welcome @Anas.


pf 4 years ago

thank you so much for this great tutorial! ;)


Andor 4 years ago

I have only one problem, I'm using the register from your tutorial and this log in form. But The password is sotred in the DB as a long number. And when I enter the pass I entered when I registered it says Username or password is incorrect.

But when I enter the pass from the db it works. Any idea how can I fix this?


itech profile image

itech 4 years ago from New Delhi, India Author

hello @Andor, you need to covert normal password into Md5 hash using md5() function of php before matching it with password stored in data base as shown below.

"$dbPass=md5($normalPass);"

The reason behind not implementing this in my script to keep it simple, so that anyone can understand machanism without any confusions.


Anas 4 years ago

I have successfully made the login and signup pages with a lot of variations ofcourse.

now i want to show the username after the user has signed in. i tried to use the $_COOKIE bit but somehow its not working. any suggestions?


itech profile image

itech 4 years ago from New Delhi, India Author

try this "echo $_COOKIE['username']", as it is.


Anas 4 years ago

alright i got it working. thanks :)


Anas 4 years ago

however wat i still dont understand is how i can 'echo' that bit in an html file.. i mean this command will be used in a php file. right? so wat if i want to display it in an html file?


itech profile image

itech 4 years ago from New Delhi, India Author

@Anas, via Somewhat like this <?php echo $_COOKIE['username']; ?>


Anas 4 years ago

i have tried that but all it shows me is a blank screen in the html file..


itech profile image

itech 4 years ago from New Delhi, India Author

View source of that html file... and then, search for that error on google or post it here. I'll try my best to assist you.


Anas 4 years ago

I wanted to see if it worked first so i only put these lines in the html file:

echo $_COOKIE['username'];

in php tags in body tags. i set the cookies in the login.php file like you mentioned. so technically it shd be working. but still the blank page


Anas 4 years ago

and i know that the cookies are set in the login.php because i m using it to redirect the user to the homepage if the user is already logged in. i m doing that with an if else statement where i use

if(!isset($_COOKIE["username"]) to check whether the cookie exists or not. if it does, then the user is redirected to the homepage. if not, then the username and password is checked against the database and new cookies are set


Anas 4 years ago

if u'd prefer, i'd post the link to my webpage here so that u can test it urself


itech profile image

itech 4 years ago from New Delhi, India Author

IF cookies are creating problems... then you should try using PHP sessions instead as shown below.

To Start or after Login:

Use:

session_start();

$_SESSION['username'] = "myUsername";

To END or TO Logout:

USE:

session_destroy();


kollyns 4 years ago

This was really helpful. Which kinds of server would you recommend. I am having some issues with my Wamp Server application....


itech profile image

itech 4 years ago from New Delhi, India Author

download and install xampp


rhon 4 years ago

thanks...that was really helpful.. :))


Rizwan 4 years ago

Thanks it is very helpful


perm 4 years ago

hello


itech profile image

itech 4 years ago from New Delhi, India Author

@perm, Hi!


Jane Samantha 4 years ago

i think this is a big crap, too many script holes, not safe to use


itech profile image

itech 4 years ago from New Delhi, India Author

In the title itself there is one word "simple".


weekendrockstar profile image

weekendrockstar 4 years ago from SE Pennsylvania

There aren't all that many holes but for any that exist..it takes just a little work to 'patch' them. Which is why this is a tutorial for the basics to show people how to store username/password credentials, how to get a user's credentials via HTML form, compare user input to credentials stored in the database and what to do when either the user is verified or not.

So this "tutorial" serves it's purpose. In the past I had mentioned using SESSIONS alongside cookies for those that do not have cookies enabled..or for when users leave the site and return later while still logged in which will still allow them access and create a new session since the server will have destroyed their previous session after X amount of time.

Obviously using MD5 (or other encryption..and I suggest using SALT for another added layer of protection) will help protect information. If someone is able to get into your database they can get unencrypted usernames but with SALT they can't simply reverse MD5 the stored password..they'd have to include the same exact random salt your PHP script uses for the password in the database to be of any value.

So yes, this CAN be more secure but that's more the point of additional tutorials on the subject where the topic is expanded. But this tutorial serves the purpose of showing one how the basics of such as system works. It isn't necessarily meant for someone to just copy/paste the code and expect to use it with a full-blow e-commerce site.

The code within the tutorial itself is good enough for simple page protection of a personal site (maybe you have a page with personal stuff that you want only certain people/friends to view)...nothing all that sensitive. However, always remember that no matter HOW strong you make your script and algorithm that if the right person wants in badly enough to put the time in that ANY system can be broken into. The point for any programmer is to make it as difficult as is possible for someone to get into.

Any "hacker" will weigh the time/energy against the value of the protected information to determine if it's really worth the effort. Obviously more people would be interested in something like Facebook rather than Bill's Personal Website...so FB would need stronger protection. But you should always make it as strong as you can. Especially when you are storing ANY personally identifiable information on your guests. But in a system like this NO personal info is stored about any user. Just a username/password that cannot be associated with a single physical human being. The only info in 'danger' is whatever the site's admin chooses to show in the "protected" areas.


itech profile image

itech 4 years ago from New Delhi, India Author

@weekendrockstar, Thanks! You are really a rockstar!


atharva 3 years ago

where to add $_COOKIE['username'] script


Sajjad 3 years ago

its simply amazing....thanks for sharing this amazing article


Spy on Boyfriend 3 years ago

Hi I really got delight from reading your post, I admire your writing style.


tbirrrd 2 years ago

Hello I just started to work with php. I copied the code, and I got the login.html page & it works fine, and I'm working on the login.php page, but the redirect code is not taking me to the website that I'm directing it to. When I use my main website that the login, and register.pages is going to be hosted on. But here's the weird thing about it. When I use Xampp and go to PhpyAdmin and set everything up there, and I go to localhost/login.html and put the from action="login.php method="post" everything works perfectly, but when I go to my webpage domain and use the domain PhpMyAdmin and setup everything there it all works, but it won't redirect me after it say's that I have logged in successfully, And I just need to know what it is that stopping me on my web hosting, VS Xampp? When I use Xampp it works flawlessly, the redirect and all. Could somebody please lead me in the right direction?

Thanks,

Tony D.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working