How To Create A Landing Page Leads Notification With Twilio SMS API and PHP

November 04, 2021
Written by
Ijeoma Nelson
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

How to Create a Landing Page Leads Notification App with Twilio's SMS API and PHP

For many digital marketers, the landing page, also known as the "squeeze" or "destination" page, is that all important single page that is designed to capture the contact details of potential buyers.

Typically part of a bigger marketing-funnel sequence, the landing page is designed to lead visitors through a journey that eventually converts them into buyers. However, in situations where the campaign objective requires a personal contact with each new lead as they arrive, a funnel system will not do the job.

Thankfully, there’s a Twilio SMS API for that!

In this tutorial, you'll learn how to build a landing page with a fully functional PHP form that sends a “you’ve got a new lead” notification via email and SMS.

Prerequisites

This tutorial assumes a basic understanding of HTML, CSS, Bootstrap, and PHP. In addition, to follow along, you need the following:

Create the landing page

First, create a folder and name it the-beauty-salon, because we're creating a landing page for a fictitious beauty business. Then, inside that directory, create two more folders: one for your CSS, named css, and the other for your images, named img.

You can do all of this by running the commands below.

mkdir -p the-beauty-salon/{css,img}

If you're using Microsoft Windows, run the following commands instead.

mkdir the-beauty-salon/css the-beauty-salon/img

Next, create a new file, index.php, with your IDE or text editor, in the top-level directory. Then, add the code below to the file.

<?php
    require  'form_validation.php';
?>

Here, we’re linking the PHP code that we’ll later create to validate our form.

Next, if your IDE has an Emmet plugin installed, then you can automatically generate a basic HTML boilerplate in index.php by typing an exclamation mark and pressing the TAB key, which will give you the following result. If you don't have an Emmet plugin, copy the code below into index.php.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
</body>
</html>

After that, update the opening HTML tag to match the following.

<html lang="en" class="h-100">

We’ll be using Bootstrap via a Content Delivery Network (CDN), so there’s no need to install anything. To load Bootstrap's CSS file, copy and place this tag before the closing head tag.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" 
    rel="stylesheet" 
    integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" 
    crossorigin="anonymous">

Then, copy and place this script tag before the closing </body> tag.

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" 
    integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" 
    crossorigin="anonymous"
    ></script> 

After that, add link tag below before the closing head tag.

<link href="css/style.css" rel="stylesheet">

Finally, change the text inside the title tag, from "Document" to the name of your project, e.g., "The Beauty Salon". We have now completed the head section of our project. Your code in index.php should look like the following.

<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="A sales page for our annual autumn beauty workshop.">
  <title>The Beauty Salon</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css">
</head>

Let’s move on to the body section of our page. Edit index.php to match the following code, keeping the trailing script tag.

</head>
  <body class="d-flex h-100 text-center text-white bg-dark">
    <div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column">
      <header class="mb-auto">
        <div>
          <h3 class="float-md-start mb-0">The Beauty Salon</h3>
          <nav class="nav nav-masthead justify-content-center float-md-end">
            <a class="nav-link active" aria-current="page" href="#">Home</a>
            <a class="nav-link" href="#">Features</a>
            <a class="nav-link" href="#">Contact</a>
          </nav>
        </div>
      </header>
      <main class="main-content">
        <?php if ($msg != ''): ?>
          <div class="alert <?php echo $alert; ?>"><?php echo $msg; ?></div>
        <?php endif; ?>
        <h1>The Beauty Workshop</h1>
        <p class="lead">How to start and scale your beauty business during these uncertain times. Our autumn workshop is dedicated to
        all the newbies in the beauty industry. Start learning how to thrive.</p>
        <p class="lead">
          <a href="#" class="btn btn-lg btn-secondary" data-bs-toggle="modal" data-bs-target="#register">Register Now</a>
        </p>
      </main>
      <footer class="mt-auto text-white-50">
        <p>Made With Love <a href="#" class="text-white">The Beauty Salon</a>, by <a
            href="#" class="text-white">Ijeoma Nelson</a>.</p>
      </footer>
    </div>

The code begins with some Bootstrap classes added to the opening body tag. Then the header tag is added to contain all the links for the navigation menu. This is followed by the main section of the page which is neatly wrapped in the main tag. Some PHP code is injected in order to display a confirmation message to the user notifying them of the success status of their form submission.

Later on in the tutorial, we’ll be using data-bs-toggle and data-bs-target to control a modal dialog, so that every time a user clicks on a “Register Now” button, the signup form will pop up. Lastly, the business credentials are added to the bottom of the landing page through the use of the footer tag.

Time to style our page with some CSS. I’ve divided the styles page into three sections. The first part deals with the header, the second section deals with the body, and the final part styles the modal dialog.

Let’s start with the first part. Using your favourite editor or IDE, create a CSS stylesheet, named style.css, in the css directory and insert the code below into it.

/*
 * Header
 */
h3 {
  color: #9b2963;
  font-size: 40px;
}

.nav-masthead .nav-link {
  padding: .25rem 0;
  font-weight: 700;
  color: #9b2963;
  background-color: transparent;
  border-bottom: .25rem solid transparent;
}

.nav-masthead .nav-link:hover {
  color: #ffffff;
}

.nav-masthead .nav-link:hover,
.nav-masthead .nav-link:focus {
  border-bottom-color: #ffffff;
}

.nav-masthead .nav-link+.nav-link {
  margin-left: 1rem;
}

.nav-masthead .active {
  color: #9b2963;
  border-bottom-color: #fff;
}

Next, we’ll add the CSS for the body of the landing page. Add the following CSS to your file.

/*
 * Body
 */
body {
  background: url("/img/adam-winger-VjRpkGtS55w-unsplash.jpg") no-repeat, center;
  background-size: cover;
}

.cover-container {
  max-width: 42em;
}

main {
  background-color: #333333;
  opacity: 0.85;
  padding: 40px 40px 40px 40px !important;
  color: #ffffff;
}

.lead {
  padding-top: 10px;
  line-height: 1.7;
}

.btn-secondary {
  background-color: #9b2963;
  border-color: #9b2963;
  color: #fff;
  padding: 12px 40px;
  font-weight: bold;
}

.btn-secondary:hover {
  background-color: #fff !important;
  border-color: #fff !important;
  color: #333;
}

You can download the background image, adam-winger-VjRpkGtS55w-unsplash.jpg, from unsplash to the img directory, in the project's root directory.

Finally, we’ll complete this section by adding the CSS for the modal dialog.

/*
* modal
*/
.modal-text {
  color: #333333;
  font-size: 20px;
  text-align: center;
  padding-bottom: 0;
  margin-bottom: 3px;
}

.modal-header {
  flex-direction: column;
  padding-bottom: 0 !important;
}

.modal-title {
  color: #9b2963;
  font-size: 25px;
}

.form-label {
  color: #333333;
}

div.mb-3 {
  text-align: left !important;
}

Install the Twilio SDK

Open up your terminal and from inside the top-level directory of your project folder run the following command:

composer require twilio/sdk

Once the installation is complete, you should see output similar to the following.

Running composer require in PhpStorm&#x27;s terminal tab.

Create the PHP form

Next, in index.php, let's add a PHP form with the help of Bootstrap’s modal-* classes, so that each time our visitor clicks on the CTA button a signup form will pop up in the window. Open index.php and add the following code just after the final closing div tag.

<div class="modal fade" id="register" tabindex="-1" aria-labelledby="registerLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="registerLabel">The Beauty Salon</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>

          <div class="modal-body"> 
            <p class="modal-text">Leave your name + email.</p>
            <p class="modal-text">We'll get back to you soon!</p>
            
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
              <div class="mb-3">
                <label for="exampleInputName1" class="form-label">Name</label>
                <input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
              </div>

              <div class="mb-3">
                <label for="exampleInputEmail1" class="form-label">Email address</label>
                <input type="email" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email : ''; ?>">
              </div>
              <button type="submit" name="submit" class="btn btn-primary">Submit</button>
            </form>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          </div>
        </div>
    </div>
</div>

This code adds the Bootstrap modal component to the CTA button. In addition, some quick preliminary frontend form validation is performed through the use of PHP’s isset() function.

Validate and sanitise form requests

It’s time to write some code to validate and sanitise the data entered into the form. Form validation is a necessary security measure because it protects your website from malicious attacks such as SQL injections, cross-site scripting, etc. In your editor or IDE, create a new file named form_validation.php in the project's top-level directory. Then, add the following code to the file.

<?php
require 'twilio_sms.php';

$msg = '';
$alert = '';

if (filter_has_var(INPUT_POST, 'submit')) {
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);

    if (!empty($name) && !empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
        $toEmail = 'msetter@twilio.com';
        $subject = 'Contact Request From ' .$name;
        $body = '<h2>Contact Request</h2><h4>Name</h4><p>'.$name.'</p><h4>Email</h4><p>'.$email.'</p>';
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "content-Type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: " .$name. "<" .$email. ">" . "\r\n";

        if (mail($toEmail, $subject, $body, $headers)) {
            send_sms($name, $email);
            unset($_POST['name']);
            unset($_POST['email']);
            $msg = "Your Email Has Been Sent";
            $alert = "alert-success";
        } else {
            $msg = "Your Email Was Not Sent";
            $alert = "alert-danger";
        }
    }

    if (empty($name) || empty($email)) {
        $msg = "Please fill in all fields";
        $alert = "alert-danger";
    } elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $msg = "Please use a valid email";
        $alert = "alert-danger";
    }
}

The code begins by requiring the Twilio SMS function that will be used to send the sms message. After that filter_has_var() is used to perform a simplistic check to confirm if the form has been submitted. If this check is not successful then the user is told to fill in all the form fields. If the check passes, checks are performed on the submitted name and email address, to ensure that they're not empty, and that the email address is valid. If these checks fail, the user is alerted with an error message. If the checks pass, the recipient's email is created.

Finally, the mail() function is used to email the data entered by the user. If the data is successfully sent, then an SMS message is sent by Twilio to notify the owner of the landing page that they’ve got a new lead. Otherwise, the visitor is alerted to the fact that their email was not sent.

Don’t forget to replace example@mail.com with your own email address otherwise your code will not work.

This completes the form validation and sanitising. The next part is to create the Twilio function that will send the SMS message.

Integrate the Twilio SMS API with the landing page.

Create a new file, twilio_sms.php, in the project's top-level directory and add the following code to it.

<?php

require __DIR__ . '/vendor/autoload.php';

use Twilio\Rest\Client;

function send_sms($name, $email)
{
    $sid = "TWILIO_ACCOUNT_SID";
    $token = "TWILIO_AUTH_TOKEN"; 

    $client = new Client($sid, $token);
    $client->messages->create(
        '+[your mobile number]', 
        [
            'from' => 'TWILIO_PHONE_NUMBER', 
            'body' => 'Congratulations! You Have A New Lead! ' . $name . " > " . $email . "."
        ]
    );
}

Here, the code begins by requiring Composer’s autoloader and importing the Twilio API. Then, it initialises a new Client instance, named $client, and passes it your Twilio Account SID and Auth Token as arguments. This object creates a message body containing your mobile phone number, Twilio number, and the notification message, through its create() function. Now, every time a user successfully submits a form, an SMS message will be sent to your mobile phone.

Retrieve Your Twilio Credentials and Phone Number

Retrieve your Twilio Account SID and Auth Token

These are required so that the code can make authenticated requests to Twilio and send the lead notification. Login to your Twilio account, and from the Twilio Console's Dashboard, copy your Account SID and Auth Token and paste them in place of the placeholder values in twilio_sms.php for TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN respectively.

Retrieve an active Twilio phone number with SMS capabilities

Then, click "Phone Numbers > Manage > Active Numbers" in the left-hand side navigation panel. From there, click the number in the "Number" column that has SMS capability. Finally, copy the "Phone Number" value, not the "Friendly Name" value, in place of TWILIO_PHONE_NUMBER in twilio_sms.php. Lastly, replace +[your mobile number] with your mobile phone number.

Test that the landing page works as expected

With the code now completed, it's time to test that it works. To do that, first start the application, using PHP's in-built webserver, by running the command below in the root directory of your project.

 

php -S 0.0.0.0:8080 -t .

Next, open your browser to http://localhost:8080 to load the landing page. It should look like the image below.

 

The Beauty Salon Landing Page

Next, click the Register Now button, which will open the modal dialog, then fill in your details and press submit. If everything worked as expected, a little while later, you should receive an SMS message on your smartphone like the one below.

Receive SMS

Congratulations on completing this tutorial. I wish you every success in getting those leads.

Ijeoma Nelson is a former Deloitte software and cloud engineer. She discovered a hidden passion for programming after winning Startup Weekend Silicon Valley. These days she can be found planning her travel adventures for 2022 whilst building cool stuff with code. You can reach her via LinkedIn or Twitter.