Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Double Opt-In Subscription Form with Secure Hash using PHP

#1
Double Opt-In Subscription Form with Secure Hash using PHP

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/double-opt-in-subscription-form-with-secure-hash-using-php.png" width="550" height="461" title="" alt="" /></div><div><p>Last modified on September 24th, 2019 by Vincy.</p>
<p>Do you know that the opening rate of emails by double opt-in confirmed subscribers is a staggering 40%? According to CampaignMonitor, email marketing generates $38 in ROI for every $1 spent.</p>
<p>Email marketing delivers the highest among any channel for marketing. Even in comparison with channels like print, TV and social media.</p>
<p><img class="alignnone size-large wp-image-10590" src="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-form-with-secure-hash-using-php-550x461.png" alt="Double Opt-In Subscription Form with Secure Hash using PHP" width="550" height="461" srcset="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-form-with-secure-hash-using-php-550x461.png 550w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...ng-php.png 940w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>Email marketing is the way to go. The primary mode to build your list is using a double opt-in subscription form.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#why-do-we-need-double-opt-in">Why do we need double opt-in?</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#what-is-the-role-of-secure-hash">What is the role of secure hash?</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#double-opt-in-subscription-form-in-php">Double opt-in subscription form in PHP</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#sequence-flow-for-double-opt-in-subscription">Sequence flow for double opt-in subscription</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#double-opt-in-subscription-form-ui">Double opt-in Subscription form UI</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#php-ajax-for-subscription-form-submission">PHP AJAX for subscription form submission</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#url-with-secure-hash">URL with secure hash</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#a-php-utility-class-for-you">A PHP utility class for you</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#store-subscription-information-to-database">Store subscription information to database</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#a-database-abstraction-layer-for-you">A database abstraction layer for you</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#send-confirmation-email-to-users">Send confirmation email to users</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#subscription-confirmation">Subscription confirmation</a></li>
<li><a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#conclusion">Conclusion</a></li>
</ol>
<p>Use a double opt-in subscription form to signup to a newsletter, blog or a similar service. It has a two-step subscription process.</p>
<p>In the first step, the user will submit his name and email. Then the site will send an email to the user.</p>
<p>In the second step, the user will click the link in the received email. This will confirm his subscription to the site or service.</p>
<blockquote readability="6">
<p>We call it the double opt-in because the users consent to the subscription twice. First by submitting the information and second by confirming to in by clicking the link in email.</p>
</blockquote>
<h2 id="why-do-we-need-double-opt-in">Why do we need double opt-in?</h2>
<p>It is the mechanism used to verify if the subscriber owns the input email. You need to do this verification because there is a chance for misuse by submitting emails that they do not own.</p>
<p><a href="https://optinmonster.com/double-optin-vs-single-optin-which-one-is-better/">Double opt-in vs single opt-in</a> is well debated and results arrived at. Double opt-in wins hands-on in every critical aspect.</p>
<h2 id="what-is-the-role-of-secure-hash">What is the role of a secure hash?</h2>
<p>In the confirmation email received by the user, there will be a link. This is the second and important step in the opt-in process. The link should be secure.</p>
<ul>
<li>It should be unique for every user and request.</li>
<li>It should not be predictable.</li>
<li>It should be immune to a brute-force attack.</li>
</ul>
<h2 id="double-opt-in-subscription-form-in-php">Double opt-in subscription form in PHP</h2>
<p>I will present you a step by step detail on how to build a double opt-in subscription form with a secure hash using PHP.</p>
<p><img class="alignnone size-medium wp-image-10612" src="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-php-project-structure-239x300.png" alt width="239" height="300" srcset="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-php-project-structure-239x300.png 239w, https://phppot.com/wp-content/uploads/20...ucture.png 550w" sizes="(max-width: 239px) 100vw, 239px"></p>
<p>You will get a production-grade code which you can use real-time in your live website. You can use this to manage your newsletter subscription.</p>
<blockquote readability="5">
<p>I am releasing this code to you under MIT license. You can use it free even in commercial projects.</p>
</blockquote>
<h2 id="sequence-flow-for-double-opt-in-subscription">Sequence flow for double opt-in subscription</h2>
<ol>
<li>Show a subscription form to the user.</li>
<li>On AJAX submit, insert a new record in the database.</li>
<li>Send an email to the user with a secure hash link.</li>
<li>On click, the of the link, update the subscription status.</li>
<li>On every step, there will be appropriate validations in place.</li>
</ol>
<h2 id="double-opt-in-subscription-form-ui">Double opt-in Subscription form UI</h2>
<p>This is where developers get it wrong. Keep it simple and unobtrusive. For the high conversion, you must keep in minimal.</p>
<p>One field email is enough for the subscription. To address the user in a personal way, you need their name. That’s it. Do not ask for much information on a subscription form.</p>
<pre class="prettyprint lang-php">&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;meta name="author" content="Vincy"&gt; &lt;link rel="stylesheet" type="text/css" href="assets/css/phppot-style.css"&gt; &lt;title&gt;Double Opt-In Subscription Form with Secure Hash using PHP&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="phppot-container"&gt; &lt;h1&gt;Double Opt-in Subscription&lt;/h1&gt; &lt;form class="phppot-form" action="" method="POST"&gt; &lt;div class="phppot-row"&gt; &lt;div class="label"&gt; Name &lt;/div&gt; &lt;input type="text" id="pp-name" name="pp-name" class="phppot-input"&gt; &lt;/div&gt; &lt;div class="phppot-row"&gt; &lt;div class="label"&gt; Email * &lt;div id="email-info" class="validation-message" data-required-message="required." data-validate-message="Invalid email."&gt;&lt;/div&gt; &lt;/div&gt; &lt;input type="text" id="pp-email" name="pp-email" class="required email phppot-input" onfocusout="return validateEmail();"&gt; &lt;/div&gt; &lt;div class="phppot-row"&gt; &lt;button type="Submit" id="phppot-btn-send"&gt;Subscribe&lt;/button&gt; &lt;div id="phppot-loader-icon"&gt;Sending ...&lt;/div&gt; &lt;div id="phppot-message"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;script src="vendor/jquery/jquery-3.3.1.js"&gt;&lt;/script&gt; &lt;script src="assets/js/subscribe.js"&gt;&lt;/script&gt;&lt;/body&gt; &lt;/body&gt; &lt;/html&gt; </pre>
<p>If you ask for much information, it will drive your users away. The same principle applies when you build a contact form. More or less these two behave in a similar aspect. Check <a href="https://phppot.com/php/simple-secure-spam-free-contact-form-in-php-iris/">how to build a contact form</a> to know more on it.</p>
<p><a href="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-confirmation-ui.png"><img class="alignnone wp-image-10594 size-full" src="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-confirmation-ui.png" alt="Double Opt-in subscription form UI" width="1718" height="786" srcset="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-confirmation-ui.png 1718w, https://phppot.com/wp-content/uploads/20...00x137.png 300w, https://phppot.com/wp-content/uploads/20...68x351.png 768w, https://phppot.com/wp-content/uploads/20...50x252.png 550w" sizes="(max-width: 1718px) 100vw, 1718px"></a></p>
<p>You should leave the name field can as optional and only the email field should be as required. This will encourage the user to submit the form and subscribe for the newsletter.</p>
<p>Needless to say, the form should be responsive. Any page or form you build should work in mobile, tablet, laptop and desktop devices. You should optimize to work on any viewport.</p>
<p>Google parses webpages in mobile mode for indexing in the search result. The desktop is an old story and gone are those days. You should always design for the mobile. Make it mobile-first!</p>
<h2 id="php-ajax-for-subscription-form-submission">PHP AJAX for subscription form submission</h2>
<p>I have used AJAX to manage the submission. This will help the user to stay on the page after subscription. You can position this subscription form in a sidebar or the footer.</p>
<p><a href="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-form-ajax-submission.png"><img class="alignnone size-full wp-image-10597" src="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-form-ajax-submission.png" alt="Double Opt-in Subscription Form AJAX Submission" width="1718" height="906" srcset="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-form-ajax-submission.png 1718w, https://phppot.com/wp-content/uploads/20...00x158.png 300w, https://phppot.com/wp-content/uploads/20...68x405.png 768w, https://phppot.com/wp-content/uploads/20...50x290.png 550w" sizes="(max-width: 1718px) 100vw, 1718px"></a></p>
<p>This is a classic example of where you should use the AJAX. I have seen instances where people use AJAX in inappropriate places, for the sake of using it.</p>
<h3>Subscription AJAX endpoint</h3>
<p>The AJAX endpoint has three major steps:</p>
<ol>
<li>Verify the user input.</li>
<li>Insert a record in the database.</li>
<li>Send an email with a link for subscription.</li>
</ol>
<p>subscribe-ep.php is the AJAX endpoint. It starts with an if condition to check if the submit is via the POST method. It is always good to program for POST instead of the GET by default.</p>
<pre class="prettyprint lang-php">&lt;?php use Phppot\Subscription; use Phppot\SupportService; /** * AJAX end point for subscribe action. * 1. validate the user input * 2. store the details in database * 3. send email with link that has secure hash for opt-in confirmation */ session_start(); // to ensure the request via POST if ($_POST) { require_once __DIR__ . './../lib/SupportService.php'; $supportService = new SupportService(); // to Debug set as true $supportService-&gt;setDebug(false); // to check if its an ajax request, exit if not $supportService-&gt;validateAjaxRequest(); require_once __DIR__ . './../Model/Subscription.php'; $subscription = new Subscription(); // get user input and sanitize if (isset($_POST["pp-email"])) { $userEmail = trim($_POST["pp-email"]); $userEmail = filter_var($userEmail, FILTER_SANITIZE_EMAIL); $subscription-&gt;setEmail($userEmail); } else { // server side fallback validation to check if email is empty $output = $supportService-&gt;createJsonInstance('Email is empty!'); $supportService-&gt;endAction($output); } $memberName = ""; if (isset($_POST["pp-name"])) { $memberName = filter_var($_POST["pp-name"], FILTER_SANITIZE_STRING); } $subscription-&gt;setMemberName($memberName); // 1. get a 12 char length random string token $token = $supportService-&gt;getToken(12); // 2. make that random token to a secure hash $secureToken = $supportService-&gt;getSecureHash($token); // 3. convert that secure hash to a url string $urlSecureToken = $supportService-&gt;cleanUrl($secureToken); $subscription-&gt;setSubsriptionKey($urlSecureToken); $subscription-&gt;setSubsciptionSatus(0); $currentTime = date("Y-m-d H:iConfused"); $subscription-&gt;setCreateAt($currentTime); $result = $subscription-&gt;insert(); // check if the insert is success // if success send email else send message to user $messageType = $supportService-&gt;getJsonValue($result, 'type'); if ('error' != $messageType) { $result = $subscription-&gt;sendConfirmationMessage($userEmail, $urlSecureToken); } $supportService-&gt;endAction($result); } </pre>
<p>I have used the SupportService class to perform common functions.</p>
<blockquote readability="8">
<p>Input sanitisation is a must. When you collect information using a public website, you should be careful. You could get infected without your knowledge. There are many bots foraging around the Internet and they click on all links and buttons.</p>
</blockquote>
<p>To sanitise, do not invent a new function. Use the function provided by PHP and that is safe to use.</p>
<h2 id="url-with-secure-hash">URL with secure hash</h2>
<p>Generate a unique url for each user subscription. Use this url to confirm the user’s subscription in the second step. Remember, that’s why we call this double opt-in.</p>
<p>I have used a three step process:</p>
<ol>
<li>Generate a random string token.</li>
<li>Convert the token to secure hash.</li>
<li>Convert the secure hash to safe url.</li>
</ol>
<p>I have used hexdec, bin2hex and openssl_random_pseudo_bytes to generate random bits. Which forms a random string.</p>
<p>Then to make the random string a secure hash, I have used the PHP’s built-in password_hash function. Never every try to do something on your own. Go with the PHP’s function and it does the job very well.</p>
<p>Before PHP 7, we had the option to supply a user generated salt. Now PHP 7 release has deprecated it. It is a good move because, PHP can generate a better salt than what you will generate. So stick to PHP 7 and use it without supplying your own salt.</p>
<p>The secure hash will contain all sort of special characters. . You can keep those special characters but need to url encode it. But I always wish to keep urls clean and the encoded chars do not look nice.</p>
<p>So no harm in removing them. So I cleanup those and leave only the safe characters. Then as a secondary precaution, I also encode the resultant string.</p>
<p>Thus after going through multi step process, we get a random, hash secure, <a href="https://perishablepress.com/stop-using-unsafe-characters-in-urls/">safe, encoded URL</a> token. Save the user submitted information in database record along with this token.</p>
<h2 id="a-php-utility-class-for-you">A PHP utility class for you</h2>
<p>This is a utility class which I use in my projects. I am giving it away free for you all. It has functions that I reuse quite often and will be handy in situations. Every method has detailed comments that explain their purpose and usage method.</p>
<pre class="prettyprint lang-php">&lt;?php /** * Copyright © 2019 Phppot * * Distributed under MIT license with an exception that, * you don’t have to include the full MIT License in your code. * In essense, you can use it on commercial software, modify and distribute free. * Though not mandatory, you are requested to attribute this URL in your code or website. */ namespace Phppot; class SupportService { /** * Short circuit type function to stop the process flow on validation failure. */ public function validateAjaxRequest() { // to check if its an ajax request, exit if not $http_request = $_SERVER['HTTP_X_REQUESTED_WITH']; if (! isset($http_request) &amp;&amp; strtolower($http_request) != 'xmlhttprequest') { $output = $this-&gt;createJsonInstance('Not a valid AJAX request!'); $this-&gt;endAction($output); } } /** * Last point in the AJAX work flow. * Clearing tokens, handles and resource cleanup can be done here. * * @param string $output * @param boolean $clearToken */ public function endAction($output) { die($output); } public function setDebug($mode) { if ($mode == true) { ini_set('display_errors', 1); set_error_handler(function ($severity, $message, $file, $line) { if (error_reporting() &amp; $severity) { throw new \ErrorException($message, 0, $severity, $file, $line); } }); } } /** * encodes a message string into a json object * * @param string $message * @param string $type * @return \JsonSerializable encoded json object */ public function createJsonInstance($message, $type = 'error') { $messageArray = array( 'type' =&gt; $type, 'text' =&gt; $message ); $jsonObj = json_encode($messageArray); return $jsonObj; } public function getJsonValue($json, $key) { $jsonArray = json_decode($json, true); return $jsonArray[$key]; } /** * If you are using PHP, this is the best possible secure hash * do not try to implement somthing on your own * * @param string $text * @return string */ public function getSecureHash($text) { $hashedText = password_hash($text, PASSWORD_DEFAULT); return $hashedText; } /** * generates a random token of the length passed * * @param int $length * @return string */ public function getToken($length) { $token = ""; $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $codeAlphabet .= "abcdefghijklmnopqrstuvwxyz"; $codeAlphabet .= "0123456789"; $max = strlen($codeAlphabet) - 1; for ($i = 0; $i &lt; $length; $i ++) { $token .= $codeAlphabet[$this-&gt;cryptoRandSecure(0, $max)]; } return $token; } public function cryptoRandSecure($min, $max) { $range = $max - $min; if ($range &lt; 1) { return $min; // not so random... } $log = ceil(log($range, 2)); $bytes = (int) ($log / 8) + 1; // length in bytes $bits = (int) $log + 1; // length in bits $filter = (int) (1 &lt;&lt; $bits) - 1; // set all lower bits to 1 do { $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))); $rnd = $rnd &amp; $filter; // discard irrelevant bits } while ($rnd &gt;= $range); return $min + $rnd; } /** * makes the passed string url safe and return encoded url * * @param string $str * @return string */ public function cleanUrl($str, $isEncode = 'true') { $delimiter = "-"; $str = str_replace(' ', $delimiter, $str); // Replaces all spaces with hyphens. $str = preg_replace('/[^A-Za-z0-9\-]/', '', $str); // allows only alphanumeric and - $str = trim($str, $delimiter); // remove delimiter from both ends $regexConseqChars = '/' . $delimiter . $delimiter . '+/'; $str = preg_replace($regexConseqChars, $delimiter, $str); // remove consequtive delimiter $str = mb_strtolower($str, 'UTF-8'); // convert to all lower if ($isEncode) { $str = urldecode($str); // encode to url } return $str; } /** * to mitigate XSS attack */ public function xssafe($data, $encoding = 'UTF-8') { return htmlspecialchars($data, ENT_QUOTES | ENT_HTML401, $encoding); } /** * convenient method to print XSS mitigated text * * @param string $data */ public function xecho($data) { echo $this-&gt;xssafe($data); } } </pre>
<h2 id="store-subscription-information-to-database">Store subscription information to the database</h2>
<p><a href="https://phppot.com/jquery/ajax-add-edit-delete-records-in-database-using-php-and-jquery/">Insert a record to the database</a> on submission of the subscription form. We get the user’s name, email, generate a secure hash token, current time, subscription status.</p>
<pre class="prettyprint lang-php">&lt;?php /** * Copyright © 2019 Phppot * * Distributed under MIT license with an exception that, * you don’t have to include the full MIT License in your code. * In essense, you can use it on commercial software, modify and distribute free. * Though not mandatory, you are requested to attribute this URL in your code or website. */ namespace Phppot; use Phppot\DataSource; class Subscription { private $ds; private $memberName; private $email; private $subsriptionKey; private $subsciptionSatus; private $createAt; private $supportService; function __construct() { require_once __DIR__ . './../lib/DataSource.php'; $this-&gt;ds = new DataSource(); require_once __DIR__ . './../lib/SupportService.php'; $this-&gt;supportService = new SupportService(); } public function getMemberName() { return $this-&gt;memberName; } public function getEmail() { return $this-&gt;email; } public function getSubsriptionKey() { return $this-&gt;subsriptionKey; } public function getSubsciptionSatus() { return $this-&gt;subsciptionSatus; } public function getCreateAt() { return $this-&gt;createAt; } public function setMemberName($memberName) { $this-&gt;memberName = $memberName; } public function setEmail($email) { $this-&gt;email = $email; } public function setSubsriptionKey($subsriptionKey) { $this-&gt;subsriptionKey = $subsriptionKey; } public function setSubsciptionSatus($subsciptionSatus) { $this-&gt;subsciptionSatus = $subsciptionSatus; } public function setCreateAt($createAt) { $this-&gt;createAt = $createAt; } /** * to get the member record based on the subscription_key * * @param string $subscriptionKey * @return array result record */ public function getMember($subscriptionKey, $subscriptionStatus) { $query = 'SELECT * FROM tbl_subscription where subscription_key = ? and subscription_status = ?'; $paramType = 'si'; $paramValue = array( $subscriptionKey, $subscriptionStatus ); $result = $this-&gt;ds-&gt;select($query, $paramType, $paramValue); return $result; } public function insert() { $query = 'INSERT INTO tbl_subscription (member_name, email, subscription_key, subscription_status, create_at) VALUES (?, ?, ?, ?, ?)'; $paramType = 'sssis'; $paramValue = array( $this-&gt;memberName, $this-&gt;email, $this-&gt;subsriptionKey, $this-&gt;subsciptionSatus, $this-&gt;createAt ); $insertStatus = $this-&gt;ds-&gt;insert($query, $paramType, $paramValue); return $insertStatus; } public function updateStatus($subscriptionKey, $subscriptionStatus) { $query = 'UPDATE tbl_subscription SET subscription_status = ? WHERE subscription_key = ?'; $paramType = 'is'; $paramValue = array( $subscriptionStatus, $subscriptionKey ); $this-&gt;ds-&gt;execute($query, $paramType, $paramValue); } /** * sends confirmation email, to keep it simple, I am just using the PHP's mail * I reccommend serious users to change it to PHPMailer and set * appropriate headers */ public function sendConfirmationMessage($mailTo, $urlSecureToken) { // following is the opt-in url that will be sent in email to // the subscriber. Replace example.com with your server $confirmOptInUrl = 'http://example.com/confirm.php?q=' . $urlSecureToken; $message = '&lt;p&gt;Howdy!&lt;/p&gt; &lt;p&gt;This is an automated message sent for subscription service. You must confirm your request to subscribe to example.com site.&lt;/p&gt; &lt;p&gt;Website Name: example&lt;/p&gt; &lt;p&gt;Website URL: http://example.com&lt;/p&gt; &lt;p&gt;Click the following link to confirm: ' . $confirmOptInUrl . '&lt;/p&gt;'; $isSent = mail($mailTo, 'Confirm your subscription', $message); if ($isSent) { $message = "An email is sent to you. You should confirm the subscription by clicking the link in the email."; $result = $this-&gt;supportService-&gt;createJsonInstance($message, 'message'); } else { $result = $this-&gt;supportService-&gt;createJsonInstance('Error in sending confirmation email.', 'error'); } return $result; } } </pre>
<p>The reason for storing the current time is to have an expiry for every link. We can set a predefined expiry for the double opt-in process.</p>
<p><img class="alignnone wp-image-10599 size-medium" src="https://phppot.com/wp-content/uploads/2019/09/subscription-information-database-structure-300x264.png" alt width="300" height="264" srcset="https://phppot.com/wp-content/uploads/2019/09/subscription-information-database-structure-300x264.png 300w, https://phppot.com/wp-content/uploads/20...ucture.png 498w" sizes="(max-width: 300px) 100vw, 300px"></p>
<p>For example, you can set one week as expiry for a link from the moment you generate it. The user has to click and confirm before that expiry period.</p>
<p>Subscription status is by default stored as ‘0’ and on confirmation changed to ‘1’.</p>
<h2 id="a-database-abstraction-layer-for-you">A database abstraction layer for you</h2>
<p>It is my PHP abstraction for minor projects. This works as a layer between controller, business logic and the database. It has generic methods using which we can to the <a href="https://phppot.com/jquery/jquery-ajax-inline-crud-with-php/">CRUD operations</a>. I have bundled it with the free project download that is available at the end of this tutorial.</p>
<h2 id="send-confirmation-email-to-users">Send confirmation email to users</h2>
<p>After you insert the record, send an email will to the user to perform the double opt-in confirmation. The user will have a link in the email which he has to click to confirm.</p>
<p>Keep the email simple. It is okay to have text instead of fancy HTML emails. PHP is capable of generating any email and you can code complex email templates. But the spam engines may not like it.</p>
<p><a href="https://phppot.com/wp-content/uploads/2019/09/subscription-information-database-record.png"><img class="alignnone size-large wp-image-10601" src="https://phppot.com/wp-content/uploads/2019/09/subscription-information-database-record-550x98.png" alt="Subscription information database record with secure hash" width="550" height="98" srcset="https://phppot.com/wp-content/uploads/2019/09/subscription-information-database-record-550x98.png 550w, https://phppot.com/wp-content/uploads/20...300x54.png 300w, https://phppot.com/wp-content/uploads/20...68x137.png 768w" sizes="(max-width: 550px) 100vw, 550px"></a></p>
<p>If you wish to go with HTML emails, then keep the HTML code ratio to as least as possible. As this is also one factor using which the spam engines flag the emails.</p>
<p>Then remember not to use the spam stop words. There are words like “free”, “win”, “cash”, “promo” and “income”. There is a long list and you can get it on the Internet by searching for “email spam filter word list”.</p>
<p>I have used PHP’s mail() function to send the email. I recommend you to change it to <a href="https://phppot.com/php/send-email-in-php-using-gmail-smtp/">PHPMailer to send SMTP based email</a> if you plan to use this code in production.</p>
<h2 id="subscription-confirmation">Subscription confirmation</h2>
<p>Create a public landing page and you may use .htaccess for a neat URL mapping. This URL should map with the URL sent to the user and the PHP file that is going to process the request.</p>
<p>As a first step, GET the token and to verify the user against the database. Check,</p>
<ol>
<li>if such a token exists,</li>
<li>it is not expired,</li>
<li>the user is not already subscribed</li>
<li>add more validation as you deem fit.</li>
</ol>
<pre class="prettyprint lang-php">&lt;?php use Phppot\Subscription; use Phppot\SupportService; /** * For confirmation action. * 1. Get the secure has from url * 2. validate it against url * 3. update the subscription status in database accordingly. */ session_start(); // to ensure the request via POST require_once __DIR__ . '/lib/SupportService.php'; $supportService = new SupportService(); // to Debug set as true $supportService-&gt;setDebug(true); $subscriptionKey = $_GET['q']; require_once __DIR__ . '/Model/Subscription.php'; $subscription = new Subscription(); $result = $subscription-&gt;getMember($subscriptionKey, 0); if (count($result) &gt; 0) { // member found, go ahead and update status $subscription-&gt;updateStatus($subscriptionKey, 1); $message = $result[0]['member_name'] . ', your subscription is confirmed.'; $messageType = 'success'; } else { // securiy precaution: do not reveal any information here // play subtle with the reported message $message = 'Invalid URL!'; $messageType = 'error'; } ?&gt; &lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;meta name="author" content="Vincy"&gt; &lt;link rel="stylesheet" type="text/css" href="assets/css/phppot-style.css"&gt; &lt;title&gt;Double Opt-In Subscription Confirmation&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="phppot-container"&gt; &lt;h1&gt;Double Opt-in Subscription Confirmation&lt;/h1&gt; &lt;div class="phppot-row"&gt; &lt;div id="phppot-message" class="&lt;?php echo $messageType; ?&gt;"&gt;&lt;?php echo $message;?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/body&gt; &lt;/html&gt; </pre>
<p>If validation fails, do not reveal any information to the user. You should only say that it has failed.</p>
<p><a href="https://phppot.com/wp-content/uploads/2019/09/subscription-double-opt-in-confirmation-url-verification.png"><img class="alignnone size-large wp-image-10602" src="https://phppot.com/wp-content/uploads/2019/09/subscription-double-opt-in-confirmation-url-verification-550x162.png" alt="Subscription double opt-in confirmation url verification" width="550" height="162" srcset="https://phppot.com/wp-content/uploads/2019/09/subscription-double-opt-in-confirmation-url-verification-550x162.png 550w, https://phppot.com/wp-content/uploads/20...300x88.png 300w, https://phppot.com/wp-content/uploads/20...68x226.png 768w" sizes="(max-width: 550px) 100vw, 550px"></a></p>
<p>More important do not say, not such email found. This will allow finding who has subscribed to your service. Whenever a validation fails, the displayed message should not reveal internal information.</p>
<p>On validation success, update the subscription status. Then show a happy success message to the user.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I have presented you with a production-grade double opt-in subscription form. I have followed a most secure hash generation method for confirmation URL email. I present it to you under the MIT license. The intention is to be the most permissible. You can download it free and change the code. You can even use it in your commercial projects. I have used the most secure code as possible. You can use this in your live site to manage newsletter subscription. In the coming part, I will include unsubscribe and enhance it further. Leave your comments below with what sort of enhancements you are looking for.</p>
<p><a class="download" href="https://phppot.com/wp-content/uploads/2019/09/double-opt-in-subscription-form-with-secure-hash-using-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/double-opt-in-subscription-form-with-secure-hash-using-php/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2019/09/...using-php/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016