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.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com 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: https://corp.maven.io/privacy-policy

Show Details
Necessary
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 googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
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)
Marketing
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.
Statistics
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)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)