PHP form Validation
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 6: PHP form Validation
In the login.php file the action is login_process.php, this file is for PHP form validation. When the user attempts to log in, the cookies and sessions are created. This is when it is important to know input names and the action used for the form. Remember, the input names are login and password, and the action used for the form is POST. Also, notice the cookies are the values for the inputs, login and password. We will talk more about this later.
login.php
<form action="login_process.php" method="post"> Username: <input type="text" name="login" value="<?php echo $_COOKIE['username']; ?>" /><br /><br /> Password: <input type="password" name="password" value="<?php echo $_COOKIE['password']; ?>"/><br /><br /> <input type="submit" value="Login" /> </form>
login_process.php
When the login button is clicked the login_process.php file is processed because it is the action to take, the first step for PHP form validation is to start the session, so it can save the information entered by the user. We do this with session_start(). We will now create three empty session containers, message, userid, and error. This is to clear the sessions from the previous log in process.
//start session to save information session_start(); //clear the message and userid sessions $_SESSION['message'] = ""; $_SESSION['userid'] = ""; $_SESSION['error'] = "";
The next step in PHP form validation is to connect to the MySQL database, we use the require_once() PHP function we talked about before and include the database connection file, config.php. Then we create two variables, $login and $password. We use the PHP function mysql_real_escape_string() to prevent SQL injection, which we talked about earlier. The $login variable is equal to the input login, since we used the POST method and the input is called login it is called $_POST[‘login’]. The $password variable is equal to the input password, since we used the POST method and the input is called password it is called $_POST[‘password’].
//Include database connection details require_once('config.php'); $login = mysql_real_escape_string($_POST['login']); $password = mysql_real_escape_string($_POST['password']);
Next, we create the first if construct to start the PHP form validation process. Also, we will use the empty() PHP function we talked about earlier. If the $login and $password variables are not empty then validate them, if they are empty then do something else. They would be empty if the user has not typed in any username and password.
if(!empty($login) && !empty($password)) { //PHP code } else { //PHP code )
If the username and password are not empty the next step is to create the query to validate that the username and password are the same as the ones in the user database. The MySQL query is “SELECT * FROM tuser WHERE username = ‘$login’ AND password = SHA(‘$password’)”, this selects all the columns from the tuser table and looks at the username in the username column and the password in the password column and makes sure it matches what was entered in by the user. Notice the username equals the $login variable and the password equals the $password variable. Also, the password is encrypted so notice how it is inside SHA, which we talked about in part 2. Then the $data variable is created, this contains the data from the executed query. We use the PHP function mysql_query() to execute the query, we talked about this in part 2 also.
$query = "SELECT * FROM tuser WHERE username = '$login' AND password = SHA('$password')"; $data = mysql_query($query);
Next, we create the second if construct, if there is data from the executed query then continue the validation process, if there is no data and the query fails to execute then do something else.
if($data) { //PHP code } else { //PHP code }
To find out if there is data we use the PHP function mysql_num_rows(), which we talked about in part 2. If it equals 1 then there is a row of data, which means there is a username and password, if it does not equal 1 then there is no data, which means there is no username or password, and it will do something else.
if (mysql_num_rows($data) == 1 ) { //PHP code } else { //PHP code }
If there is data then the $row variable is created. This variable uses the PHP function mysql_fetch_assoc(), which uses the information from variable $data and returns an array, or a special variable where multiple values are stored in one single variable. This array creates a variable for each column in the tuser table.
Then we create the sessions, userid, username, and fname. They contain the user information from the $row array variable created. The PHP code for the array variables are $row[‘column_name’], so the userid is $row[‘userid’]. The session userid contains the userid column in the tuser table. The session username contains the username column from the tuser table. The session fname contains the firstname column from the tuser table.
$row = mysql_fetch_assoc($data); $_SESSION['userid'] = $row['userid']; $_SESSION['username'] = $row['username']; $_SESSION['fname'] = $row['firstname'];
We continue with the validation and now create the username and
password cookies to save for the user. This allows the user to log in automatically next time they go to the site. The PHP code to create a cookie is setcookie(‘cookie_name’, data_used, expire_time, path), so in this guide we use “setcookie(‘username’, $login, time()+3600*24*30, “/”);”. The username is the cookie name and the data from the $login variable is used, which is the username the user entered at log in. The expiration is 30 days, in PHP 30 days is “time()+3600*24*30”. The path used is “/” because it means the cookie is available within the entire domain. Remember from part 1, the value of the input login was $_COOKIE[‘login’] and the value of the password input was $_COOKIE[‘password’]. This enters the username and password automatically for the user if the cookie exists. If it has been more than 30 days the user would have to enter it in again.
setcookie('username', $login, time()+3600*24*30, "/"); setcookie('password', $password, time()+3600*24*30, "/");
We continue with the validation and now create the message session, which contains a message to the user for when they log in successfully. It says welcome, and then shows their first name using the fname session. The PHP code is “Welcome, ” . $_SESSION[‘fname’]; Notice how welcome is in double quotes and then there is a dot then the session fname. You need to use the dot to separate the written text from the PHP code. After the session is created you are redirected to the member page, member.php, using the PHP function header() which we talked about in part 2. Then you use the PHP function exit() to terminate the script.
$_SESSION['message'] = "Welcome, " . $_SESSION['fname']; header('Location: member.php'); exit();
We continue with the third if construct and add an else. If mysql_num_rows($data) does not equal 1 then there is no data or the user did not enter the correct username and password combination. So the error session is created, it contains the error message “Please enter a valid username or password. Not registered? “Please enter a valid username or password. Not registered? Please <a href=”signup.php”>sign-up</a>”, you are then redirected to the error.php page where the error is displayed and the user has to log in again. The PHP script then terminates with exit().
if (mysql_num_rows($data) == 1 ) { //PHP code } else { $_SESSION['error'] = 'Please enter a valid username or password. Not registered? Please <a href="signup.php">sign-up</a>'; header('Location: error.php'); exit(); }
Continuing with the second if construct we add an else. If the query fails to execute then exit the script and display the message, query failed, using the PHP die() function.
if($data) { //PHP code } else { die("Query failed"); }
Continuing with the first if construct we add an else to it. If the $login and $password variables are empty then this means the user did not enter a username or password and clicked the login button. So the session error is created and contains the message ‘Please enter a username or password. Not registered? Please <a href=”signup.php”>sign-up</a>’. The user is then redirected to the error.php page where the error is displayed and the user has to log in again. The PHP script then terminates with exit().
if (mysql_num_rows($data) == 1 ) { //PHP code } else { $_SESSION['error'] = 'Please enter a valid username or password. Not registered? Please <a href="signup.php">sign-up</a>'; header('Location: error.php'); exit(); }
Full Code:
<?php //Start session session_start(); $_SESSION['message'] = ""; $_SESSION['userid'] = ""; //Include database connection details require_once('config.php'); $login = mysql_real_escape_string($_POST['login']); $password = mysql_real_escape_string($_POST['password']); if(!empty($login) && !empty($password)) { $query = "SELECT * FROM tuser WHERE username = '$login' AND password = SHA('$password')"; $data = mysql_query($query); if($data) { if (mysql_num_rows($data) == 1 ) { $row = mysql_fetch_assoc($data); $_SESSION['userid'] = $row['userid']; $_SESSION['username'] = $row['username']; $_SESSION['fname'] = $row['firstname']; setcookie('username', $login, time()+3600*24*30, "/"); setcookie('password', $password, time()+3600*24*30, "/"); $_SESSION['message'] = "Welcome, " . $_SESSION['fname']; header('Location: member.php'); exit(); } else { $_SESSION['error'] = 'Please enter a valid username or password. Not registered? Please <a href="signup.php">sign-up</a>'; header('Location: error.php'); exit(); } } else { die("Query failed"); } } else { $_SESSION['error'] = 'Please enter a username or password. Not registered? Please <a href="signup.php">sign-up</a>'; header('Location: error.php'); exit(); } ?>
Now that the log in process is finished we will work on user access control in part 4, which will complete the PHP & MySQL user account tutorial.