Simple Php Login or Signin Script
By itech
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:
- Create a separate page for this php script.
- 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.
- 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.
- 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).
Comments
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.
I see.
But It's necessary to a minimum.
Otherwise this script is with a friend of PHP sucks.
mysql_real_escape_string() should take care of most SQL injection issues. Looks like you already fixed it.
where is the mysql syntax or creating the table please can you specify i am new here hope you can send me a complete details ronjersan@gmail.com
Another wonderful hub...Thanks.
That was extremely useful!
I'm trying to create an admin area for my website, so that will certainly help!
Thanks :)
@deutsched , Glad to see that it will help you.
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.
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)
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).
how we can save logout time in database when user wish to logout and not by cookie
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.
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
Hi itech, can u tell me how to modify the php script after i used the md5 function in registration script ?
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...
@sasajib, Thanks for pointing it out.... I will correct it now.
thank you...
Little type in the form above:
form metod="POST" s/b method
Yup... It's small but a big Bug/Mistake... Very much thankful to you @steve
hiii
i create login log out script..
when i login , dashboard page diaplay page of login user
now perss refresh button ...
i still not stay on this page..
give solution abot that plz
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.
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);
1) Read second paragraph of this article,
2) And then, Add new records in login table (Username + Password combination). OR
Read this article : http://itech.hubpages.com/hub/Registration-script
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 didnt 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.
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.
what is the "include("template_file_address");" plzzz??
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.
is it optional?
Yes, It is Optional!
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.
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>
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.
Thanks itech for replying so soon. I'll let you know if I encountered anymore errors.
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? :/
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.
very good idea
@madhu, thnx for commenting.
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?
i think the header() function will not work if echo is used before it.
@Anas, You can use this [Click Here: http://itech.hubpages.com/hub/Simple-Php-Login-Scr] 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");
}
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.
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.
You are always welcome @Anas.
thank you so much for this great tutorial! ;)
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?
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.
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?
try this "echo $_COOKIE['username']", as it is.
alright i got it working. thanks :)
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?
@Anas, via Somewhat like this <?php echo $_COOKIE['username']; ?>
i have tried that but all it shows me is a blank screen in the html file..
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.
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
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
if u'd prefer, i'd post the link to my webpage here so that u can test it urself
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();
This was really helpful. Which kinds of server would you recommend. I am having some issues with my Wamp Server application....
download and install xampp
thanks...that was really helpful.. :))
Thanks it is very helpful
unknown 23 months ago
Opps...SQL Injection...