Learn MySQL & PHP Tutorial for Beginners: PHP Login Session

MySQL PHP User Account Tutorial

MySQL PHP Tutorial 1: MySQL User accounts
MySQL PHP Tutorial 2: PHP login Session
MySQL PHP Tutorial 3: PHP Form Validation
MySQL PHP Tutorial 4: PHP User Access Control

 

MySQL PHP Tutorial Step 5: Creating a PHP login session

To start the PHP login session we will first write the code for signup.php and then we can start saving user information. The PHP code to start the session is “session_start();”. In this guide I added it to the header.php file, and included it in signup.php. The include() function allows you to include a file into your current PHP file. This stops you from having to keep writing the same HTML or PHP code over and over again. The code to include a file is include(“file.php”);”.

signup.php

<?php include("header.php"); ?>

<head>
<title>First login PHP Script</title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
</head>

<body>

<div id="content">

<div id="header"></div>

<div id="nav"></div>

<div id="right">
<form action="signup_process.php" method="post">
<span class="fname"> 
<label for="firstname">First Name:</label><input name="fname" type="text"/><br />
</span>
<span class="lname"> 
<label for="lastname">Last Name:</label><input name="lname"  type="text" /><br />
</span>
<span class="mail">
<label for="emailaddress">Email:</label><input name="email" type="text"  /><br />
</span>
<span class="uname"> 
<label for="username">Username:</label><input name="username"  type="text"/><br />
</span>
<span class="pass1"> 
<label for="password1">Password:</label><input name="password1"  type="password" /><br />
</span>
<span class="pass2"> 
<label for="password2">Password (retype):</label><input name="password2"  type="password" /><br />
</span>
<input type="submit" value="Sign Up" name="submit" class="submit" />

</form>
</div>

</div>

<?php include("footer.php"); ?>

signup_process.php

The signup_process.php file is identical to the signup.php file, except the PHP code will be written in it. The first step is connecting to the MySQL database so the user can sign up. To do this we will include the config.php we created in part 1. To include it we will use the PHP require_once() function, it will check to see if the file has been included, if not it will include it.

//Include database connection file
 require_once('config.php');

Next we will grab the user information typed into the form. This is when it is important to remember the names of each input type and the method used to grab the data from the form. We will use an if construct to check to see if the signup button has been clicked. To tell PHP to check this, we use isset. The isset checks to see whether the input name, submit, from the form has been created or set, if it has it returns true. Since we used the POST method we use $_POST[‘input_name’] to tell PHP which POST we are checking or using in the form. In this guide it is the signup button named submit, so it is $_POST[‘submit’].

if(isset($_POST['submit']))  {

//PHP Code

}

Next, we are going to create a different variable for each input the user has entered into the form. The PHP code to create this is “$variable = mysql_real_escape_string($_POST[‘input_name’]);”. We use mysql_real_escape_string for SQL injection prevention, which is another topic all together. What mysql_real_escape_string does though is remove the quotes in a string and replace them with escaped quotes for use in SQL.

//create the input variables and prevent SQL injection
$username = mysql_real_escape_string($_POST['username']);
$password1 = mysql_real_escape_string($_POST['password1']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email = mysql_real_escape_string($_POST['email']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);

The next step is to make sure that the username and password fields are not empty and the passwords variables are equal. We start a second if construct and use the empty() PHP function, which checks to see if the variable is empty or not. In PHP !empty means not empty, so we use “if(!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2))”.

//check to make sure that the username and password fields are not empty and that the passwords match
if(!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2)) 

{ //PHP Code  } 

elseif ($password1 != $password2) 

{ //PHP Code }

else

{ //PHP Code  }

The next step is to make sure the username does not already exist in the table. To do this we create a variable called query for the MySQL query. The code is “$query = “SELECT * FROM tuser WHERE username = ‘$username’;”. The Query selects all columns from table tuser, * means all columns, where the username equals the username entered, notice how the username variable was used again for the username. We get the information from the executed MySQL query and create a variable called data that contains the data. The MySQL query is executed using mysql_query($query). The code is “$data = mysql_query($query);”. We use another if construct, the data variable, and the mysql_num_rows() function to make sure that no usernames exist in the table. The code to check for no username looks like this, “if(mysql_num_rows($data) == 0)”. If there is no row created with the username from the data then the user’s data is inserted into the table.

//make sure the username does not already exist, create sql query to check username
$query = "SELECT * FROM tuser WHERE username = '$username' "; 

//the data variable connects to the database and executes the MySQL query
$data = mysql_query($query);

//check to make sure no username row exists in the data, if data is empty or zero
if(mysql_num_rows($data) == 0)  

{ //PHP Code }

else 

{ //PHP Code }

The next step is to create the MySQL query to insert the user’s data into the table, the query variable is created for the query, the code is, $query = “INSERT INTO tuser (username, password, email, firstname, lastname, join_date) VALUES (‘$username’, SHA(‘$password1’), ‘$email’, ‘$fname’, ‘$lname’, NOW() )”; After INSERT INTO tuser the column names are used and after VALUES the input variables are used. Notice the password variable is inside SHA, SHA is a MySQL command to encrypt the data.

//query variable to insert user data
$query = "INSERT INTO tuser (username, password, email, firstname, lastname, join_date) VALUES ('$username', SHA('$password1'), '$email', '$fname', '$lname', NOW() )";

The query executes and the session signup is created, the signup session contains the sign up confirmation message. If the session is not started you will not be able to create any session containers. Remember, we started the session using “session_start();” in the header.php file.

 //executes the query
 mysql_query($query);           

//The PHP login session is created, confirms success with user      
$_SESSION['signup'] = '</pre>
<p>Your new account has been sucessfully created. You\'re now ready to log in and edit your profile</p>';

After confirmation of a successful sign up, close the connection to the database, create the userid session, and redirect them to another page where they can login. The code to close the database connection is, “mysql_close($link);” the link variable is the connection variable in the config.php file. You create the userid session for access control purposes, we will discuss this later. You use the header() PHP function to redirect someone to another page. The PHP code for a redirect is, “header(“Location: success.php”);”. In this guide you are redirected to the success.php page. After the redirect you use the PHP code, “exit();” which terminates the script.

//closes the connection to the database    
mysql_close($link);

//creates the PHP login session for the userid
$_SESSION['userid'] = "0";

//redirect to the PHP file success.php, on a successful log in
header('Location: success.php');

//terminates php script
exit();

We continue with the third if construct and add an else. If the number of rows with the username entered is not equal to 0, show the message that an account already exists with that username, you use the PHP echo to display the message.

if(mysql_num_rows($data) == 0)   

{ //PHP Code }

else

{ //an account already exists for this username, so display error message

echo'<p class="error">An account already exists for this username, Please use a different name</p>';

//clear username variable so that the form is cleared
$username=""; }

The next line of code continues the second if construct and adds an elseif and an else to it. If the passwords do not match, display a message. If information is missing, display a message that you need to fill out all the information to continue.

if(!empty($username) && !empty($password1) && !empty($password2) &&   ($password1 == $password2))

{ //PHP Code    }     

elseif ($password1 != $password2)

{ //show message if passwords do not match

echo'<p>The Passwords do not match</p>'; }

else

{ //show message that information is missing

echo'<p>You must enter all information to sign up</p>'; }

The last line and final line closes the connection to the database

mysql_close($link);

Full Code:

<?php

//Include database connection file
require_once('config.php');

//when the signup button is clicked, grab data from the form using POST
if(isset($_POST['submit']))

{ //create the input variables and prevent SQL injection

$username = mysql_real_escape_string($_POST['username']);
$password1 = mysql_real_escape_string($_POST['password1']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email = mysql_real_escape_string($_POST['email']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);

//check to make sure that none of the fields are empty and that the passwords match
if(!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2))

{ //make sure the username does not already exist, create sql query to check username

$query = "SELECT * FROM tuser WHERE username = '$username' "; 
$data = mysql_query($query);

//the data variable connects to the database and executes the MySQL query

//check to make sure no username row exists in the data, if data is empty or zero

if(mysql_num_rows($data) == 0) 

{ //query variable to insert user data

$query = "INSERT INTO tuser (username, password, email, firstname, lastname, join_date) VALUES ('$username', SHA('$password1'), '$email', '$fname', '$lname', NOW() )";

//executes query above
mysql_query($query);           

//The signup session is created, confirms success with user      
$_SESSION['signup'] = '<p>Your new account has been sucessfully created. You\'re now ready to log in and edit your profile</a></p>';

//closes the connection to the database    
mysql_close($link);

//creates the session for the userid
$_SESSION['userid'] = "0";

//redirect to the PHP file success.php, on a successful log in
header('Location: success.php');

//terminates php script
exit(); }

else

{ //an account already exists for this username, so display error message

echo'<p>An account already exists for this username, Please use a different name</p>';

//clear username variable so that the form is cleared
$username=""; }

}

elseif ($password1 != $password2)

{  echo'<p>The Passwords do not match</p>';  }

else

{ echo'<p>You must enter all information to sign up</p>'; }

}

mysql_close($link);

?>

Now that the sign up process is complete, part 3 will be about PHP form validation and how to save a cookie.

Share:

About Author

Enjoys Nature. Electronic Music. Design. Hockey. Being Inspired.

Leave a Comment