ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Create login and logout form in PHP with MySql Database.

Updated on August 16, 2015


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. (Will connect your database with your PHP pages)
  2. (Will help to get the current page reference)
  3. (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.


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 ''

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


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


'' 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 ''

$current_file = $_SERVER['SCRIPT_NAME'];

  $http_referer = $_SERVER['HTTP_REFERER'];
 $http_referer = '';

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

?> 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 ''

$username = $_POST['username'];
$password = $_POST['password'];

//echo $password_hash;

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

$data = mysql_fetch_array($query);


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

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">
</div> 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'

require '';
header('Location: '.$http_referer);


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

5. Save this page as 'index.php'

require '';
require '';
 $result = mysql_query("SELECT * FROM users WHERE id = $rightvar") or die(mysql_error());  
               $data = mysql_fetch_array($result);  
   echo 'Welcome! ' . $firstname . ' ' . $surname .'<a  href="logout.php"><input type="button"  value="Logout"/></a>';
include '';

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 .


then the above page will appear.

then enter

username: Mike007

Password : friesian


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'

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

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


Please comment if you like my Hub.


    0 of 8192 characters used
    Post Comment

    • profile image

      Ryan Ramlall 15 months ago

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

    • profile image

      Sigrun 2 years 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

      akhila tantry 2 years ago

      I get only error like this..

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

      How can I resolve this?

      please help me..

    • profile image

      JOY 2 years ago


    • profile image

      mnau 2 years ago

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

    • profile image

      Suraj 2 years ago

      please help me ,

      In this code fatal error in

    • profile image

      tej123 2 years ago

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

    • friesian profile image

      friesian 2 years 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

      Shailesh 2 years ago

      Invadid username/password combination.

      display this error

    • profile image

      Erwin 2 years ago

      Help me please :(

      how to fix please!!

      Cant connect :Unknown database 'test-login'

    • profile image

      siva 2 years ago

      its shows error in line 2; error is parse error ot T_string error

    • profile image

      PETER GOTSIS 2 years ago

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

    • profile image

      Sugashini 2 years ago

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

    • profile image

      Syed Khaleel 3 years ago

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

    • profile image

      Nitesh 3 years ago

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

      plz help

    • profile image

      chirag 3 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

      Sandeep 3 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

      obed 3 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

      Devraj 3 years ago

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

    • profile image

      saurabh 3 years ago

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

    • profile image

      Shah 3 years ago

      it is not working please help me

    • profile image

      Tshepho Motala 3 years ago

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

    • friesian profile image

      friesian 3 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


      To generate MD5 password manually follow the last heading.

      "How to generate md5 for manual database filling?"

    • profile image

      ganesh12345 3 years ago

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

    • profile image

      mayur 3 years ago

      Invadid username/password combination

    • profile image

      Mian Adnan 3 years ago

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

    • profile image

      Shasha 3 years ago

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

    • profile image

      lenlen 3 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

    • friesian profile image

      friesian 4 years ago

      Hi Herve,

      Please recheck or recreate your and files.

      You're getting this error because your page is not able to call page .

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

      Hope this will work..

      Good luck

    • friesian profile image

      friesian 4 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.

    • profile image

      divyesh 4 years ago

      Unknown column 'username' in 'where clause'

      this error generate

    • profile image

      herve 4 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\ on line 45 Call Stack #TimeMemoryFunctionLocation 10.0619142552{main}( )..\ " method="POST"

      please i need help!

    • profile image

      Sunil Yadav 4 years ago

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

    • profile image

      aisling 4 years ago

      so helpful..thanks

    • profile image

      aman 4 years ago

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

    • profile image

      jeetz 4 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 .'

    • friesian profile image

      friesian 4 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 4 years ago


      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

      friesian 5 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

      BEBS 5 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?

    • profile image

      bebs 5 years ago

      nice. ty

    • friesian profile image

      friesian 5 years ago

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

    • profile image

      punit 5 years ago

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

    • profile image

      deepti 5 years ago

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


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: ""

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)