ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Create login and logout form in PHP with MySql Database.

Updated on August 16, 2015

Requirements:

If you're beginner or new to php or MySql(database) then complete the following requirements first.

Above software are open source.

Make sure:

Before you code your first php page, make sure your Xampp is working and the first two check boxes are checked for Apache and MySql with a message ' Running '. And don't bother about filezilla.



Now open your browser and type 'localhost' (remove single quotes), if your Xampp was installed successfully then a default Xampp window will appear automatically.




Create a database in just 8 simple steps:

Now first you need to have a database to get user's log in/out status, to create a database first you have to open your browser and type in navigation bar 'localhost' then by default xampp page will appear then click on PhpMyAdmin link which is at somewhere down the page in tools section.




then click database.






Now enter the name of your database 'test-login' and click create.






Now your database will appear in this list. You have to click on your database but here in my case it's 'test-login'.





Now create tables in your database. First enter the name of your table(of your choice) and then enter the number of columns will it contain. For your convenience i would like to suggest you, first write the columns names over a rough paper and think about their role in your database and also think about their size and behavior.




Now you have to create columns in your recently created table. Enter the columns name and their "type" (type of data you want to store like INT for integer and VARCHAR for character set ) and don't forget to fill their "length". Try to set the length near minimum-required.In my case.

  • id = 20
  • username = 25
  • password = 50 (password will be md5 encrypted that's why it need quite large number.)
  • firstname = 15
  • surname = 15




now you have to set one primary key it is required because no two user could have same id. Thus first you have to set the index value for 'id' to PRIMARY KEY and check 'AI' for auto-increment. Checked 'AI' will help you to set the values in 'id', by automatically adding value 1 to the last entered value. For example if your last user registered with id '46',then you do not need to set 'id' to '47' for another user it will be automatically set by default.





Now click save.






Huray ! congratulation !

Now you have one database with one table and 5 columns in it. You're almost half done.





Now it's time to enter some raw data just for checking the log in/out function.


Click users











Click "Insert" tab.





Now you have to enter some raw data.

Leave the id column blank because the id will be automatically filled.









values for 1st column.

Now enter username = friesian

password = 12345 = md5 conversion =827ccb0eea8a706c4c34a16891f84e7b

"use md5 conversion password because it helps to increase your security level. whenever user will enter 12345 as password this phrase will automatically converted in to md5 conversion . So it doesn't effect the user login process but still increase the security."

firstname = Philip

surname = Adison

values for 2nd column.

username = Mike007

password = friesian = md5 conversion = 8e90d73bfe408221fe71f7dbfee80770

Note: Enter this in password field "8e90d73bfe408221fe71f7dbfee80770"

firstname= Mike

surname= Williams

After filling data click 'GO'.





Start writing your PHP pages:

Before you start i would like to suggest you, to use notepad++ because it is easy to use and shows your code in different colors which will help you in many aspects later in deep programming. But it is not required you can use any text editor of your choice.

Now you need at least 5 PHP pages for a successful log in/out process.

  1. connection.inc.php (Will connect your database with your PHP pages)
  2. core.inc.php (Will help to get the current page reference)
  3. login.inc.php (Will check for the log in status)
  4. logout.php (Will log out the user if he/she is logged in)
  5. index.php (Home page)

before i explain how these pages will work, first open your text editor and create these empty pages in directory and make sure your saving these files as dot(.)php.

C:\xampp\htdocs

create a directory here 'login'

now save your pages here C:\xampp\htdocs\login\

make sure your xampp directory is at first level where your operating system is installed.

after creating these empty pages copy and paste code below in these pages respectively.


1. Save this page as 'connection.inc.php'

<?php
$dbc = mysql_connect('localhost','root','') or  die("Cant connect :" . mysql_error());

mysql_select_db("test-login",$dbc)

or
die("Cant connect :" . mysql_error()); 

?>


'connection.inc.php' helps to connect your database with your php pages. You don't need to write connection codes in every page because this is an include php page which means you can use this page in any of your php page where database connection is required.

2. Save this page as 'core.inc.php'

<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];

if(isset($_SERVER['HTTP_REFERER']))
{
  $http_referer = $_SERVER['HTTP_REFERER'];
} 
else
{
 $http_referer = '';
}


function loggedin()
{
if (isset($_SESSION['user_id'])&&!empty($_SESSION['user_id']))
{
return true;
}
else
{
return false;
}
}

?>


core.inc.php helps to get the current address of the page from where the user is requesting for the log in/out request. This is required because if there are many pages in your website then you would like to give service of log in/out to your user from any page. This page also start session for your user. Like if your user is at page one and then reaches the page two then he/she don't need to login again for that page.

3. Save this page as 'login.inc.php'

<?php
if(isset($_POST['username'])&&isset($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$password_hash=md5($password);

//echo $password_hash;

if(!empty($username)&&!empty($password))
{
$query = mysql_query("SELECT * FROM users WHERE username ='".$username."' AND password ='".$password_hash."'") or die(mysql_error()); 

$data = mysql_fetch_array($query);

$test=$data['password'];

$query_run=$query;
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==0)
{
echo 'Invadid username/password combination.';
}
else if($query_num_rows==1)
{
echo 'ok';
$user_id= mysql_result($query_run,0,'id');
$user_id=$data['id'];
$_SESSION['user_id'] = $user_id;
header("Location:".$_SERVER['PHP_SELF']. " ");
}
{
}

}
else
{
echo 'You must supply a username and password';
}

}

?>
<div align="center">
<form action="<?php echo $current_file; ?>" method="POST">
Username: <input type="text" name="username"> Password: <input type="password" name="password">
<input type="submit" value="Log in">
</form>
</div>


login.inc.php is the main engine because this page first check for the entered username and password combination, and then if user is supplying valid information then it fetch the other information about the user from the database and process the login request.

4. Save this page as 'logout.php'

<?php
require 'core.inc.php';
session_destroy();
header('Location: '.$http_referer);


?>


logout.php ends the session of the user if he/she is online.

5. Save this page as 'index.php'

<?php 
require 'core.inc.php';
require 'connection.inc.php';
if(loggedin())
 {  
 $rightvar=$_SESSION['user_id'];
 $result = mysql_query("SELECT * FROM users WHERE id = $rightvar") or die(mysql_error());  
               $data = mysql_fetch_array($result);  
   $firstname=$data['firstname'];
   $surname=$data['surname'];
   $userid=$data['id'];
   
   echo 'Welcome! ' . $firstname . ' ' . $surname .'<a  href="logout.php"><input type="button"  value="Logout"/></a>';
 }
else
{
include 'login.inc.php';
}
?>



This is your home page. this page sends request for log in/out status if user is not logged in then it shows the log in form otherwise it shows the First-name and Surname of the user and a logout link.












Now test log in/out process.

open your browser and type in navigation bar .

localhost/login/index.php

then the above page will appear.

then enter

username: Mike007

Password : friesian

or

username: friesian

password: 12345


Enjoy !!


How to generate md5 for manual database filling?

there am adding one more simple md5 generating page you just need to enter some value then this page will show you the md5 code for that value.

Save this page as 'md5.php'

<?php
echo '<div align="center">
<form action="md5.php" method="POST">
Enter anything <input type="text" name="md5"> 
<input type="submit" value=" Generate md5">
</form>
</div>';
if(isset($_POST['md5']) and !empty($_POST['md5']))
{
$md5=md5($_POST['md5']);

echo '</br></br><strong>md5 conversion for "'. $_POST['md5'] . ' " is ' . $md5. ' </strong>' ;

}
?>

Please comment if you like my Hub.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      deepti 4 years ago

      nyc work...helped me a lot in strtng mah 1st project in php...

    • profile image

      punit 4 years ago

      its not working giving me the error invalid username and password tried a lot

    • friesian profile image
      Author

      friesian 4 years ago

      @Punit : Please check your database or recheck your md5 encoding ...

    • profile image

      bebs 4 years ago

      nice. ty

    • profile image

      BEBS 4 years ago

      hey i tried your codes and it works but then when i try another user to login it doesn't work anymore. what to do?

    • friesian profile image
      Author

      friesian 4 years ago

      @bebs : If one user is login without any error then it means the login process is working. But when you're trying to enter another user you need to manually fill the database. While doing this first you need the Username and the Password. You can enter username without encode it to another form, But while entering the password you need to encode it though md5 conversion. I've attached the md5.php page there after step 12. save this page as md5.php. And then generate the md5 password for the original password through. Like your password is "bebs@bebs" thus you need to first convert the "bebs@bebs" to its md5 conversion then fill the md5 conversion into password field of your database. Try this hope it will work for you.

    • profile image

      jeetz 3 years ago

      Hi!

      Thanks for such detailed guide. The only problem I face is, after successful user log in, how do I redirect to the page they were trying to access (the page I want to secure).

    • friesian profile image
      Author

      friesian 3 years ago

      @Jeetz : The code present in index.php are required for every page where there is a log in required. If user is already logged in then user will not be asked for login again for every page. But if user is logged out and trying to access any page then he will be asked for login.

      After this line inside if statement in index.php you can write your code of your secure page.

      echo 'Welcome! '

    • profile image

      jeetz 3 years ago

      Gosh! Friesian, I don't know what I am doing wrong. It just keeps giving me this error when I input my code.

      Parse error: syntax error, unexpected ' ' in C:\xampp\htdocs\index.php on line 13

      On line 13 I have following; anything I input in this line gives me above mentioned error.

      echo 'Welcome! ' . $firstname . ' ' . $surname .'

    • profile image

      aman 3 years ago

      getting an error that the memory space allocated is wrong please help!!

    • profile image

      aisling 3 years ago

      so helpful..thanks

    • profile image

      Sunil Yadav 3 years ago

      Hi my name is sunil yadav i am indian your code is good for help me

    • profile image

      herve 3 years ago

      please help, I had a problem with your code that comes up on my browser like that:

      ( ! ) Notice: Undefined variable: current_file in C:\wamp\www\PLaP\login.inc.php on line 45 Call Stack #TimeMemoryFunctionLocation 10.0619142552{main}( )..\login.inc.php:0 " method="POST"

      please i need help!

    • profile image

      divyesh 3 years ago

      Unknown column 'username' in 'where clause'

      this error generate

    • friesian profile image
      Author

      friesian 3 years ago

      Hi divyesh.

      The error "Unknown column" means your Mysql query doesn't match the database structure.

      How to fix:

      1. Check your database and tables and read the column names, their may be any spelling mistake or May be Uppercase or Lowercase mismatch. If it doesn't work,

      2. check you're using backticks (``) not apostrophe('') , `username` not 'username' . Because in mysql query backticks tells it's a column/table/database whereas apostrophy tells its data.

      Hope this will work..

      Good luck.

    • friesian profile image
      Author

      friesian 3 years ago

      Hi Herve,

      Please recheck or recreate your core.inc.php and login.inc.php files.

      You're getting this error because your login.inc.php page is not able to call core.inc.php page .

      And the other reason could be you wamp server... Try Latest Xampp

      Hope this will work..

      Good luck

    • profile image

      lenlen 2 years ago

      hi i have my prepared webpage but how can i put those codes on that?, i tried to put it but it doesn't work

    • profile image

      Shasha 2 years ago

      Parse error: syntax error, unexpected '{' in D:\xampp\htdocs\email1\index.php on line

    • profile image

      Mian Adnan 2 years ago

      I am facing the error msg : "Invadid username/password combination"

    • profile image

      mayur 2 years ago

      Invadid username/password combination

    • profile image

      ganesh12345 2 years ago

      hi please solve this invalid username /password combination problem..

    • friesian profile image
      Author

      friesian 2 years ago

      Mian Adan, Mayur , Ganesh : Please use MD5 encrypted password. The possible reason you're getting this error msg because you may be not using md5 encrypted password.

      Like you username is: ABCD

      and your password is: 12345

      Then your password's encrypted MD5 will be : 827ccb0eea8a706c4c34a16891f84e7b

      So, save MD5 in your database password field. and login with your actual password.

      Username: ABCD

      Password:12345

      To generate MD5 password manually follow the last heading.

      "How to generate md5 for manual database filling?"

    • profile image

      Tshepho Motala 2 years ago

      Hey i can't save my files in C:\xampp\htdocs so what should i do?

    • profile image

      Shah 2 years ago

      it is not working please help me

    • profile image

      saurabh 2 years ago

      please tell how to make sign up page which automatically save the data into database table

    • profile image

      Devraj 2 years ago

      Nyc post frnd...it really help me a lot... Thank you vry much

    • profile image

      obed 2 years ago

      hi, please i have create a form to submit information to my xampp database and i want to create the connection after i have create the database and table in my xampp??

    • profile image

      Sandeep 2 years ago

      getting below mentioned error. Please suggest me what to do

      Parse error: syntax error, unexpected '$rightvar' (T_VARIABLE) in C:\xampp\htdocs\login\index.php on line 6

      my code is same as you written earlier.

    • profile image

      chirag 2 years ago

      the code you gave gives me the following error when i try to access the directory:

      Parse error: syntax error, unexpected '$rightvar' (T_VARIABLE) in C:\xampp\htdocs\login\index.php on line 6

      Please help me with possible mistakes..

    • profile image

      Nitesh 2 years ago

      i have tried 100 times and every times it says "Invadid username/password combination."

      plz help

    • profile image

      Syed Khaleel 2 years ago

      I am facing the error msg : "Invadid username/password combination"

    • profile image

      Sugashini 23 months ago

      hi please solve this invalid username /password combination problem..

    • profile image

      PETER GOTSIS 22 months ago

      Great article and it is very helpful for me. how to create login form in PHP.

    • profile image

      siva 22 months ago

      its shows error in connection.inc.php line 2; error is parse error ot T_string error

    • profile image

      Erwin 21 months ago

      Help me please :(

      how to fix please!!

      Cant connect :Unknown database 'test-login'

    • profile image

      Shailesh 21 months ago

      Invadid username/password combination.

      display this error

    • friesian profile image
      Author

      friesian 21 months ago

      All of those getting invalid username/password combination please follow each step again while creating Database. Because you are not filling md5 conversion of password in password field. You need to enter md5 conversion value in it not the text version.

    • profile image

      tej123 20 months ago

      "Table 'test-login.users' doesn't exist" it is showing this comment!!! what to do???

    • profile image

      Suraj 16 months ago

      please help me ,

      In this code fatal error in connection.inc.php

    • profile image

      mnau 16 months ago

      really its very good code but plz make simple its very difficult for fresher php developer

    • profile image

      JOY 16 months ago

      PLEASE ME. OBJECT NOT FOUND AND ERRORS

    • profile image

      akhila tantry 14 months ago

      I get only error like this..

      Fatal error: Call to undefined function mysql_connect() in C:\xampp\htdocs\login\connection.inc.php on line 2

      How can I resolve this?

      please help me..

    • profile image

      Sigrun 14 months ago

      I get this error:

      Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\login\index.php on line 5

      in the beginning of :,,Now test log in/out process."

      what could be wrong? I'm copying your code so it is exactly the same.

    • profile image

      Ryan Ramlall 3 months ago

      hey I tried this, and im getting an error 403 access forbidden

    Click to Rate This Article