Make PHP Sites

Last updated: 2015-02-28

PHP user registration

In this section, we'll go over how to create a user registration system.

The code for this version will be written in a procedural method.

Requirements

Refer to the Get Started section to know what you need to use this tutorial. You must also have an understanding of HTML and how a web page is constructed.

We'll go through this assuming you know how to make an HTML form and use a MySQL database.

Prerequisites

Since this tutorial is an introduction to a database and table, there are no prerequisites. This database and table will be used in other lessons.

Contents

The MySQL database

To create this user registration app, we'll need a database. We will be using a MySQL database. Feel free to use any kind with which you are familiar as long as you can adapt our code to fit correctly.

Database name: social

We'll use this database for more social apps

Table: users

Column Type Description
userID INT (11) This will be the primary key. It is a unique ID number assigned to each individual user. It should be set to increment automatically.
email Varchar (250) This will hold the user's email address. They'll use this to log into your site.
password Text The user's password will be encrypted.
salt Int (11) "salt" will be used to encrypt they user's password.
isDeleted Bool A TRUE/FALSE value that will be used to tell if a user has canceld there account or has been blocked.
timestamp Timestamp A time stamp, provided by the database, about time the account was created or last updated.

The HTML form

Create a PHP web page file with a form for your users to register.

					<html>
						<head>
							<title>Register</title>
						</head>
						
						<body>
							
							<h1>Register</h1>
							
							<form action="" method="post">
							
								<p>
									<label for="email">Your email address</label>
									<br/>
									<input type="text" name="email" id="email" />
								</p>
								
								<p>
									<label for="password">Your password</label>
									<br/>
									<input type="password" name="password" id="password" />
								</p>
								
								<p>
									<button type="submit">Register</button>
								</p>
								
							</form>
							
						</body>
					</html>
				
Registration form image

With that form, we'll be able to gather the user's email address and password. Leave the method="post" so the user's submitted data won't be displayed in the URL. We're leaving the action="" blank so the PHP can remain on just this page.

Beginning the PHP

The array $_POST will hold the user's submitted information. It is a global variable and is available on the page whether the user has submitted the form or not. To prevent this from processing an empty $_POST, we'll set up a simple if() conditional about the HTML.

					<?php
						// Did the user submit the form?
						if(!empty($_POST)){
							// Process the form
						}
					?>
					
					<html>
					
					[...]
				

The $_POST is empty and/or NULL by default. That conditional will prevent anything from happening unless the form is submitted. Next, we'll take the variables out of the $_POST array for use.

Getting the $_POST variables

Once the form is submitted, the $_POST array will be holding the variables from it. The form we have will carry two variables, $_POST['email'] and $_POST['password'].

					<?php
						// Did the user submit the form?
						if(!empty($_POST)){
							// Process the form
							
							$email = $_POST['email'];
							$password = $_POST['password'];
						}
					?>
					
					<html>
					
					[...]
				

Now we have the variables from the $_POST array in separte variables. We could work through the whole process with them in the $_POST array, but htis simplifies it. Next, let's make sure both fields are valid.

Validating the form fields

We want to avoid bad data as often as possible. So, let's make sure the user has submitted real, valid data.

PHP has two functions that we will be using. We'll use the function trim() to see if the password was left blank or with only spaces. We'll use function filter_var() to make sure the email address is formatted like an email address. We'll use a conditional if() to judge whether or not the process should continue.

					<?php
						// Did the user submit the form?
						if(!empty($_POST)){
							// Process the form
							
							$email = $_POST['email'];
							$password = $_POST['password'];
							
							$check_password = trim($password);
							
							$check_email = filter_var($email, FILTER_VALIDATE_EMAIL);
							
							if($check_password !='' && $check_email !== FALSE){
								// Continue the process
							}
							else {
								$error = 'Please provide a valid email address and password.';
							}
						}
					?>
					
					<html>
					
					[...]
				

The function trim() removes any spaces at the start and end of the string in $password. The function filter_var, when told to FILTER_VALIDATE_EMAIL, makes sure the string $email looks like an email address. Note: different server settings might handle filter_var differently. Some settings consider user@website to be a valid address, while others consider user@website.com to be valid.

Notice the variable, $error. We'll use that later on to tell the user something went wrong. If everything went well, we'll get started with a connection to the database.

Connecting with the database

If the user's email address and password checked out, let's connect to the database and prepare to add the new user. We'll use the PHP built-in class MySQLi to do it. Let's take a look into the if() conditional that approved the email address and password.

					if($check_password !='' && $check_email !== FALSE){
						// Continue the process
						
						// What's the address of your database?
						$database_host = 'localhost';
						
						// What's the username to connect?
						$database_user = 'root';
						
						// What's the password for that user?
						$database_password = 'password';
						
						// What's the name of the database?
						$database = 'social';
						
						// User the MySQLi class to connect to database
				        $mysqli = new mysqli($database_host, $database_user, $database_password, $database);
						
						$email = $mysqli->real_escape_string($email);
						$password = $mysqli->real_escape_string($password);
						
						
						
						
						// Always close the database connection
						$mysqli->close();
					}
				

Once we had a connection to the database, we were able to use a function built into the class MySQLi, real_escape_string(). That function analyzed the strings and cleaned them up, if necessary, to protect the database from queries a user might be sending. Even though we validated the username and password, We should still sanitize them.

Salting the password

Remember the column in the database table called salt? That column is going to hold a number used to help encrypt the user's password. We will use the PHP function time() to get a long integer and append it to $password. Then, we'll use the PHP function sha1 to encrypt it.

					if($check_password !='' && $check_email !== FALSE){
						/*
							Database connection stuff
						*/
						
						// User the MySQLi class to connect to database
				        $mysqli = new mysqli($database_host, $database_user, $database_password, $database);
						
						$email = $mysqli->real_escape_string($email);
						$password = $mysqli->real_escape_string($password);
						
						$salt = time();
						
						// Append the $salt to the $password
						$password .= $salt;
						$password = sha1($password);
						
						
						
						
						// Always close the database connection
						$mysqli->close();
					}
				

The function time() produces a long integer. It is the number of seconds that have passed since midnight, January 1st 1970. It's called the Unix Epoch. At this second, the time() value looks like this: 1603521760

The function sha1 will scramble the new comination of time and password. If the password entered was 'RealWorld' and the time() addition made it 'RealWorld1603521760', after encrypting it with sha1(), the password would look like this: 5418e1a9c28cc550c942241fa674b2c738d74e85

With this method, even if fifty people type the same password, it will always look different when encrypted. Later on, when we are working on a log-in system, the user won' need to remeber the encrypted password. The stored salt value will help the system figure out what the encrypted version of their password should be.

Checking if the email address is already registered

We can't let an email address be registered more than once. So, let's query the datbase with the MySQLi class to see if it finds any.

					if($check_password !='' && $check_email !== FALSE){
						/*
							Database connection stuff
							
							Validation and password stuff
						*/
						
						$sql = "SELECT COUNT(email) AS found_email FROM users WHERE email='" . $email . "'";
						$query = $mysqli->query($sql);
						
						if($query)
							$found = $query->fetch_assoc();
						else
							$found = FALSE;
						 
						if($found == FALSE || $found['found_email'] == 0){
							// Continue the registration process
						}
						else {
							$error = 'Sorry, that email address has already registered.';
						}
						
						
						
						
						// Always close the database connection
						$mysqli->close();
					}
				

The database query is asked to cound the number of rows in table users that have an email address matching the one the user submitted. Then, the conditional if() statement checks if there are zero. If there are zero, the process would continue. Otherwise, an error message is prepared.

Assuming the email address does not exist in the database, we'll continue to insert the new user.

Inserting a new user

It's time to insert a new user into the database! Let's look into the conditional if() statement that confirmed the email address is new.

					if($check_password !='' && $check_email !== FALSE){
						/*
							Database connection stuff
							
							Validation and password stuff
							
							Query stuff
						*/
						
						if($found['found_email'] == 0){
							// Continue the registration process
							
							$sql = "INSERT INTO users "
								. "(email, password, salt) "
								. "VALUES('" . $email . "', '" . $password . "', " . $salt . ")";
								
							$query = $mysqli->query($sql);
							
							// Get the userID of the new user
							$userID = $mysqli->insert_id;
							
							// Start a session to recognize the user
							session_start();
							$_SESSION['userID'] = $userID;
							$_SESSION['email'] = $email;
							
							// Send the new user somewhere
							header('Location: /some-other-page.php');
						}
						else
							$error = 'Sorry, that email address has already registered.';
						
						
						
						
						// Always close the database connection
						$mysqli->close();
					}
				

Congratulations! You've now registered a new user.

Notice the variable $userID. Each user has a unique ID. The class MySQLi has a variable called insert_id. That variable contains the unique ID of the last entered query, your newest user's ID number.

Notice session_start(), $_SESSION['userID'] and $_SESSION['email']. Those $_SESSION is a global array, a bit similar to $_POST and $_GET. Any file that has session_start() available in it's code or code of a file attached to it can access the $_SESSION array. It is useful if you want to display the user's email address somewhere on their screen, use their ID number for something or any other purposes with different session values.

Notice the header() function. This function will send the user to another website or another page. Since this is a registration tool, it would send the user to their profile, an account management page, anywhere. Note: always have a space between Location: /some-other-page.php'. If you don't, it causes an error in some versions of IE.

What if there were errors?

Remember the $error variable we created in a few places in case the use gave bad information or if the email address was already registered? If there is an error like those, we want to display them to the user. So, we'll add an if() conditional to the web page HTML in alternative syntax.

					<html>
						<head>
							<title>Register</title>
						</head>
						
						<body>
							
							<h1>Register</h1>
							
							<?php if(isset($error)): ?>
								

<?php echo $error; ?>

<?php endif; ?> <form action="" method="post"> <p> <label for="email">Your email address</label> <br/> <input type="text" name="email" id="email" /> </p> <p> <label for="password">Your password</label> <br/> <input type="password" name="password" id="password" /> </p> <p> <button type="submit">Register</button> </p> </form> </body> </html>

Registration form errors

Registration form errors

All of the code

					<?php
						// Did the user submit the form?
						if(!empty($_POST)){
							// Process the form
							
							$email = $_POST['email'];
							$password = $_POST['password'];
							
							$check_password = trim($password);
							
							$check_email = filter_var($email, FILTER_VALIDATE_EMAIL);
							
							if($check_password !='' && $check_email !== FALSE){
								// Continue the process
								
								// What's the address of your database?
								$database_host = 'localhost';
								
								// What's the username to connect?
								$database_user = 'root';
								
								// What's the password for that user?
								$database_password = 'password';
								
								// What's the name of the database?
								$database = 'social';
								
								// User the MySQLi class to connect to database
								$mysqli = new mysqli($database_host, $database_user, $database_password, $database);
								
								$email = $mysqli->real_escape_string($email);
								$password = $mysqli->real_escape_string($password);
								
								$salt = time();
								
								// Append the $salt to the $password
								$password .= $salt;
								$password = sha1($password);
								
								$sql = "SELECT COUNT(email) AS found_email FROM users WHERE email='" . $email . "'";
								$query = $mysqli->query($sql);
								
								if($query)
									$found = $query->fetch_assoc();
								else
									$found = FALSE;
								 
								if($found == FALSE || $found['found_email'] == 0){
									// Continue the registration process
									$sql = "INSERT INTO users "
										. "(email, password, salt) "
										. "VALUES('" . $email . "', '" . $password . "', " . $salt . ")";
										
									$query = $mysqli->query($sql);
									
									// Get the userID of the new user
									$userID = $mysqli->insert_id;
									
									// Start a session to recognize the user
									session_start();
									$_SESSION['userID'] = $userID;
									$_SESSION['email'] = $email;
									
									// Send the new user somewhere
									header('Location: /some-other-page.php');
								}
								else {
									$error = 'Sorry, that email address has already registered.';
								}
								
						
						
						
								// Always close the database connection
								$mysqli->close();
							}
							else {
								$error = 'Please provide a valid email address and password.';
							}
						}
					?>
					
					<html>
						<head>
							<title>Register</title>
						</head>
						
						<body>
							
							<h1>Register</h1>
							
							<?php if(isset($error)): ?>
								

<?php echo $error; ?>

<?php endif; ?> <form action="" method="post"> <p> <label for="email">Your email address</label> <br/> <input type="text" name="email" id="email" /> </p> <p> <label for="password">Your password</label> <br/> <input type="password" name="password" id="password" /> </p> <p> <button type="submit">Register</button> </p> </form> </body> </html>

Contact us

Questions or problems? Want to contribute to this tutorial or others?

Contact us