This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
In this tutorial, we are going to create a user signup form that adds a user to a database and then sends out a confirmation email that the user must click on before their account is activated.
Create a Sign Up Form From Scratch
In this section, we will go through the steps required to build a custom sign-up form from scratch. First of all, I have attached all the code files for you to download, so that you can follow along with the tutorial.
Let's quickly go through the important files.
- index.php: It's main file which is used to build and display the sign-up form. It also handles the submission of the form as well.
- confirm.php: It's used to handle the confirmation part.
- signup_template.html: It's the HTML file template which is used to build the HTML email body.
- signup_template.txt: It's the plain text file template which is used to build the plain text email body.
- inc/php/config.php: It holds the database connection information.
The rest of the files are helper files.
Open up PHPMyAdmin or whatever program you use to manage your MySQL database, and create a new database. You can name it whatever you like, but we will name it email_signup. Now, we need to create the schema which will hold our user information and confirmation information. To do this, we will create two tables: users
and confirm
.
1 |
CREATE TABLE `users` ( |
2 |
`id` int(11) NOT NULL auto_increment, |
3 |
`username` varchar(50) NOT NULL default '', |
4 |
`password` varchar(128) NOT NULL default '', |
5 |
`email` varchar(250) NOT NULL default '', |
6 |
`active` binary(1) NOT NULL default '0', |
7 |
PRIMARY KEY (`id`) |
8 |
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
The above MySQL statement will create a table named users
with the following columns:
- id: An auto-incrementing integer column which serves as the primary key for each user record.
-
username: It's a string column which stores the username of each user. It is defined as
varchar(50)
, meaning that it can hold up to 50 characters. -
password: A string column which stores the hashed password of each user. It is defined as
varchar(128)
, meaning that it can hold up to 128 characters. -
email: A string column which stores the email address of each user. It is defined as
varchar(250)
, meaning that it can hold up to 250 characters. -
active: A binary column which stores whether the user's account has been activated or not. It is defined as
binary(1)
, meaning that it can store a single bit.
Next, let's create the confirm
table.
1 |
CREATE TABLE `confirm` ( |
2 |
`id` int(11) NOT NULL auto_increment, |
3 |
`userid` varchar(128) NOT NULL default '', |
4 |
`key` varchar(128) NOT NULL default '', |
5 |
`email` varchar(250) default NULL, |
6 |
PRIMARY KEY (`id`) |
7 |
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
The above MySQL statement will create a table named confirm
with the following columns:
- id: An auto-incrementing integer column which serves as the primary key for each user record.
-
userid: It's a string column which stores the user ID of the user who is being confirmed. It is defined as
varchar(128)
, meaning that it can hold up to 128 characters. -
key: A string column which stores the confirmation key which is sent to the user's email address. It is defined as
varchar(128)
, meaning that it can hold up to 128 characters. -
email: A string column which stores the email address of the user who is being confirmed. It is defined as
varchar(250)
, meaning that it can hold up to 250 characters.
Connect to the MySQL Database With mysqli
In this section, we'll see how to connect with the MySQL database by using the mysqli extension.
Let's quickly pull and understand the code of the inc/php/config.php file.
1 |
<?php
|
2 |
//connect to the database
|
3 |
$mysqli = new mysqli('localhost', 'root', 'root', 'email_signup'); |
4 |
|
5 |
//check if connection was successful
|
6 |
if ($mysqli->connect_errno) { |
7 |
die("Failed to connect to MySQL: " . $mysqli->connect_error); |
8 |
}
|
Firstly, we create a new mysqli
object and use it to connect to the database. If the connection fails, it will output an error message with the reason for the failure.
Setting Up Symfony Mailer for Sending Emails
Symfony Mailer is a popular library for sending emails from PHP applications, and it's widely accepted by the PHP community. It's a feature-rich library in the sense that it covers almost every aspect of sending emails, from setting up different transports to customizing the message that's being sent. Also, if you've heard of the Swift Mailer library, it's the predecessor of the Symfony Mailer library—Symfony Mailer is the new and improved version.
In this section, I'll show you how to install and configure the Symfony Mailer library. The installation is pretty straightforward, as it's already available as a Composer package. Before we go ahead, make sure you've installed Composer because we'll need it to install the Symfony Mailer library.
Once you've installed Composer, grab the Symfony Mailer library using the following command.
1 |
$composer require symfony/mailer
|
So that's the installation part, but how are you supposed to use it? It's just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.
1 |
<?php |
2 |
require_once './vendor/autoload.php'; |
3 |
?> |
Create the Sign-Up Form
Go ahead and open the index.php file which contains the following code which builds the sign-up form.
1 |
<form method="post" action=""> |
2 |
<fieldset>
|
3 |
<ul>
|
4 |
<li>
|
5 |
<label for="username">Username:</label> |
6 |
<input type="text" name="username" /> |
7 |
</li>
|
8 |
<li>
|
9 |
<label for="password">Password:</label> |
10 |
<input type="password" name="password" /> |
11 |
</li>
|
12 |
<li>
|
13 |
<label for="email">Email:</label> |
14 |
<input type="text" name="email" /> |
15 |
</li>
|
16 |
<li>
|
17 |
<input type="submit" value="Signup Now" class="large blue button" name="signup" /> |
18 |
</li>
|
19 |
</ul>
|
20 |
</fieldset>
|
21 |
</form>
|
It is an HTML form code which creates a user signup form with username, password and email fields. When the user clicks the Signup Now button, the form data will be sent to the server as a POST request.
Saving Information to the Database
Once the form is submitted, the same index.php file handles the form submission. Let's try to understand what's going on in the following snippet.
1 |
if (isset($_POST['signup'])) { |
2 |
//cleanup the variables
|
3 |
//prevent mysql injection
|
4 |
$username = mysqli_real_escape_string($mysqli, $_POST['username']); |
5 |
$password = mysqli_real_escape_string($mysqli, $_POST['password']); |
6 |
$email = mysqli_real_escape_string($mysqli, $_POST['email']); |
7 |
|
8 |
//quick/simple validation
|
9 |
if(empty($username)){ $action['result'] = 'error'; array_push($text,'You forgot your username'); } |
10 |
if(empty($password)){ $action['result'] = 'error'; array_push($text,'You forgot your password'); } |
11 |
if(empty($email)){ $action['result'] = 'error'; array_push($text,'You forgot your email'); } |
12 |
|
13 |
if ($action['result'] != 'error') { |
14 |
$password = md5($password); |
15 |
|
16 |
//add to the database
|
17 |
$add = $mysqli->query("INSERT INTO `users` VALUES(NULL,'$username','$password','$email',0)"); |
18 |
|
19 |
if ($add) { |
20 |
//get the new user id
|
21 |
$userid = $mysqli->insert_id; |
22 |
|
23 |
//create a random key
|
24 |
$key = $username . $email . date('mY'); |
25 |
$key = md5($key); |
26 |
|
27 |
//add confirm row
|
28 |
$confirm = $mysqli->query("INSERT INTO `confirm` VALUES(NULL,'$userid','$key','$email')"); |
29 |
|
30 |
...
|
31 |
...
|
32 |
...
|
33 |
|
34 |
} else { |
35 |
$action['result'] = 'error'; |
36 |
array_push($text,'User could not be added to the database. Reason: ' . mysql_error()); |
37 |
}
|
38 |
}
|
39 |
|
40 |
$action['text'] = $text; |
41 |
}
|
First of all, it checks if the form was submitted by checking if the signup
key is present in the $_POST
array.
After that, we sanitize the data entered in the form by using the mysqli_real_escape_string
function. This function helps to prevent SQL injection attacks.
Next, we perform a couple of checks to ensure that the user has entered username, password, and email. If any of these are missing, an error is added to an array of errors.
If there are no errors, we'll go ahead and insert the user's details into the database. It hashes the password using the md5
function before inserting it into the database. Please note that we've used the md5
function just for the example purposes, I would suggest you to use more secure methods to encrypt the password field. If the insertion is successful, it gets the ID of the newly added user and generates a random key based on the user's details and the current date. It then adds a row to the confirm
table with the user's ID, key, and email.
Sending an Email With Symfony Mailer
Finally, let's go through the following snippet of the index.php file which is responsible for sending an email.
1 |
//include the swift class
|
2 |
require_once './vendor/autoload.php'; |
3 |
|
4 |
//put info into an array to send to the function
|
5 |
$info = array( |
6 |
'username' => $username, |
7 |
'email' => $email, |
8 |
'key' => $key |
9 |
);
|
10 |
|
11 |
//send the email
|
12 |
if(send_email($info)){ |
13 |
//email sent
|
14 |
$action['result'] = 'success'; |
15 |
array_push($text,'Thanks for signing up. Please check your email for confirmation!'); |
16 |
} else { |
17 |
$action['result'] = 'error'; |
18 |
array_push($text,'Could not send confirm email'); |
19 |
|
20 |
}
|
In the above snippet, it calls the send_email
function, which actually sends an email. Let's pull in the code of the send_email
function from the inc/php/functions.php file.
1 |
function send_email($info){ |
2 |
//format each email |
3 |
$body = format_email($info,'html'); |
4 |
$body_plain_txt = format_email($info,'txt'); |
5 |
|
6 |
$transport = new SendmailTransport(); |
7 |
$mailer = new Mailer($transport); |
8 |
$email = (new Email()); |
9 |
$email->from('noreply@sitename.com'); |
10 |
$email->to($info['email']); |
11 |
$email->subject('Welcome to Site Name'); |
12 |
$email->text($body_plain_txt); |
13 |
$email->html($body); |
14 |
$result = $mailer->send($email); |
15 |
|
16 |
return $result; |
17 |
}
|
As you can see, it's a pretty straightforward function which sends an email with the help of the Symfony Mailer library. It's important to note that we've used the format_email
custom function to prepare the email body for both plain-text and HTML versions.
So that's how the form submission works. In the next section, we'll discuss how the confirmation part works.
Show the Form Confirmation
Let's pull in the important snippet from the confirm.php file to understand how it works.
1 |
...
|
2 |
...
|
3 |
$email = mysqli_real_escape_string($_GET['email']); |
4 |
$key = mysqli_real_escape_string($_GET['key']); |
5 |
|
6 |
//check if the key is in the database
|
7 |
$check_key = $mysqli->query("SELECT * FROM `confirm` WHERE `email` = '".$email."' AND `key` = '".$key."' LIMIT 1"); |
8 |
|
9 |
if($check_key->num_rows != 0) { |
10 |
|
11 |
//get the confirm info
|
12 |
$confirm_info = $check_key->fetch_assoc();
|
13 |
|
14 |
//confirm the email and update the users database
|
15 |
$update_users = $mysqli->query("UPDATE `users` SET `active` = 1 WHERE `id` = '".$confirm_info['userid']."' LIMIT 1");
|
16 |
|
17 |
//delete the confirm row
|
18 |
$delete = $mysqli->query("DELETE FROM `confirm` WHERE `id` = '".$confirm_info['id']."' LIMIT 1");
|
19 |
|
20 |
if($update_users){
|
21 |
|
22 |
$action['result'] = 'success';
|
23 |
$action['text'] = 'User has been confirmed. Thank-You!';
|
24 |
|
25 |
}else{ |
26 |
|
27 |
$action['result'] = 'error';
|
28 |
$action['text'] = 'The user could not be updated Reason: '.mysql_error();;
|
29 |
|
30 |
}
|
31 |
|
32 |
}else{ |
33 |
|
34 |
$action['result'] = 'error';
|
35 |
$action['text'] = 'The key and email is not in our database.';
|
36 |
|
37 |
}
|
38 |
...
|
39 |
...
|
Basically, it's used to check a user's email and confirmation key, stored in the database, against what was passed in through the URL. Firstly, it selects a row from the confirm
table in the database, looking for a matching email
and key
. If there is no match, an error is returned. If there is a match, it fetches the confirmation information from the database and updates the users
table to set the user as active. It then deletes the confirmation row from the confirm
table, as it is no longer needed.
Conclusion
And with that, we've reached the end of this tutorial.
We have covered many different areas in this tutorial. We downloaded and included a 3rd-party script to handle sending emails, implemented simple form validation, and created a super-simple template system to style our emails. If you are new to MySQL, we have touched on the three most common functions, so you should have no problem completing more advanced tutorials.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
Sajal Soni | Sciencx (2014-01-20T02:10:22+00:00) How to Code a Signup Form with Email Confirmation. Retrieved from https://www.scien.cx/2014/01/20/how-to-code-a-signup-form-with-email-confirmation/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.