Simple php login and logout script using php session and database using MySQL

This tutorial will explain how to login and logout the web page using php session and database using MySql. By using this login script, we can show the secure pages after the login page successfully logged in. For authentication process we have to create login page with username and password input field. By using the input box, we can get the username and password using php post method which is secure after submitting the form.

First we have to create a database and enter some dummy user information’s. In tutorial I’m using the WAMP Server 2.0 which has the MySQL and apache services which will run the php files.

STEP1: Create Database and Table using MySQL

Find the below image which show how to Open the phpmyadmin (Php my admin is for creating the MySQL database)

Once the browser opens the phpmyadmin page, Enter the database name inside “create new database” field and click create button. For this tutorial we using database name as “user”. Find the image below

After the database created, click the SQL link from the top menu and paste the following sql query into the text area and click go button below the textarea. Please find the image below

Post Method: We used post method to get the values, because post method is secure way to pass the username and password. Post method is the best practice when we passing the secure data’s.

Include the config.php in login.php to connect the database:Using php “include()” function include the config.php in login.php.

Session:Session is used to start the session and store the values in session and get the values anywhere in the web pages. To start the session, call the session_start() function in login.php file.

Mysql_Num_Rows: Mysql_Num_Rows function is used to return a number of rows from the table.

Step 4: Create home.php

Create the home.php file which has the script to destroy the session. When a user submit their username and password in login page, php login script will check the given username and password in the database table using MySQL select query, if the query return the value, script will redirect to home.php page. If username or password is wrong system will show error message as “User Name Or Password Invalid”.

Step 5: Destroy the session once the user clicks the logout link from home.php page

Create the logout.php file and paste the below code in to the logout.php file. Logout will destroy the session and redirect to login.php page again.