Double Opt-In Subscription Form with Secure Hash using PHP

How to write a PHP double opt-in subscription form

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.

          

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.

setDebug(false); // to check if its an ajax request, exit if not $supportService->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->setEmail($userEmail); > else < // server side fallback validation to check if email is empty $output = $supportService->createJsonInstance('Email is empty!'); $supportService->endAction($output); > $memberName = ""; if (isset($_POST["pp-name"])) < $memberName = filter_var($_POST["pp-name"], FILTER_SANITIZE_STRING); >$subscription->setMemberName($memberName); // 1. get a 12 char length random string token $token = $supportService->getToken(12); // 2. make that random token to a secure hash $secureToken = $supportService->getSecureHash($token); // 3. convert that secure hash to a url string $urlSecureToken = $supportService->cleanUrl($secureToken); $subscription->setSubsriptionKey($urlSecureToken); $subscription->setSubsciptionSatus(0); $currentTime = date("Y-m-d H:i:s"); $subscription->setCreateAt($currentTime); $result = $subscription->insert(); // check if the insert is success // if success send email else send message to user $messageType = $supportService->getJsonValue($result, 'type'); if ('error' != $messageType) < $result = $subscription->sendConfirmationMessage($userEmail, $urlSecureToken); > $supportService->endAction($result); > 
  1. if such a token exists,
  2. it is not expired,
  3. the user is not already subscribed
  4. add more validation as you deem fit.
setDebug(true); $subscriptionKey = $_GET['q']; require_once __DIR__ . '/Model/Subscription.php'; $subscription = new Subscription(); $result = $subscription->getMember($subscriptionKey, 0); if (count($result) > 0) < // member found, go ahead and update status $subscription->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'; >?>          
">

Answer by Rowan Richard

If the string is wrong, do nothing and output an error. If it’s correct, delete the row from the table and add it to another table that has confirmed emails in it (or, have a field called is_confirmed and change this to TRUE once the email has been confirmed).,How to store the temporary id-s for the double opt-in system. I thought about using something like md5 («email» . «passphrase») for the id generation and storing them next to the email addresses.,He receives an email with an URL where he needs to click. The link should not contain the email address but some md5 or random string,I am trying to write a small PHP script for managing subscriptions for a mailing list. I was trying to find whatever resources I can find over the internet but I only came up with:

Caveat: Code hasn’t been tested so syntax and other errors are possible.

[email protected]'; $dbHost = 'localhost'; $dbUser = 'dbuser'; $dbPass = 'dbpass'; $dbDatabase = 'dbname'; mysql_connect($dbHost, $dbUser, $dbPass); mysql_select_db($dbDatabase); $ip = $_SERVER["REMOTE_ADDR"]; if ( isset( $_GET['key'] ) && isset( $_GET['email'] ) ) < // If we have 'email' and 'key' parameters, we are handling an opt-in click $email = mysql_real_escape_string( $_GET['email'] ); // Check if key matches hash of email and salt combination and if email is really an email if ( sha1( $email.$salt ) == $_GET['key'] && filter_var($email, FILTER_VALIDATE_EMAIL) ) < // Check if entry already exists $checkDupes = mysql_query( "SELECT COUNT(*) as cnt FROM emails WHERE email = '$email'"; ); $result = mysql_fetch_assoc($checkDupes); if ($result['cnt'] < 1) < // Fresh email, insert into db along with remote ip and timestamp mysql_query( "INSERT INTO emails (email, ip, timestamp) VALUES ( '$email', $ip, NOW() );" ); die('Subscription confirmed!'); >else < die('Email already exists in database'); >> else < die('Key mismatch or invalid email!'); >> else if ( isset( $_POST['email'] ) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) < // Form submission, send confirmation email $email = $_POST['email']; $key = sha1( $email.$salt ); $link = $url . '?email=' . $email . '&key=' . $key; $mailSubject = 'Please confirm your subscription'; $mailTo = $email; $mailBody = 'Please confirm your subscription by clicking this link'; $headers = 'From: ' . $fromEmail . "\r\n"; mail( $mailTo, $mailSubject, $mailBody ); > else < // Present form and show error if needed if ( isset( $_POST['email'] ) ) < echo "Ivalid email submitted!
"; > echo '
Email:
'; >

Answer by Emberly Morgan

Schedule a demo to see the Mailgun platform in action.,Email MarketingEngage with customers with the right campaign at the right time.,Get up and running fast to start making the most of Mailgun.,Creating a signup with Mailgun can be trivial. I receive tons of messages from people asking me to write a tutorial on how to do this in PHP so here it is. Before talking code, let’s briefly discuss best practices. If you know everything about double opt-in, skip the next paragraph and move on to the engineering part.

The first thing you will want to do is create a form that you will have somewhere on your website. This form will ask people for their details that you can save in a database or if supported, within the email platform itself. Mailgun supports the latter (and even more when using custom variable parameters), so you don’t have to worry about having to set up a database to hold this data.

The form will post to a file called contact.php and will have two fields that are mandatory. You can obviously make the name field non-mandatory or add more, but for the purpose of this article, we will keep it simple!

Answer by Braylee Hughes

This code shows how to perform an Email-based double-opt-in registration using PHP and MySQL., Perform an Email-based double-opt-in registration using PHP and MySQL. , Perform an Email-based double-opt-in registration using PHP and MySQL. ,It is intended as a complement to my tutorial: http://tonygaitatzis.tumblr.com/post/66610863603/double-opt-in-email-registration

$settings['mysql']['server'] = 'localhost'; $settings['mysql']['username'] = 'mysqluser'; $settings['mysql']['password'] = 'mysqlpassword'; $settings['mysql']['schema'] = 'optin_example'; 

Answer by Kinsley Stevens

To ensure that all subscribers of your email list really wanted to subscribe, you can enable the double opt-in requirement.,To immediately subscribe someone, and skip sending a confirmation email, you can call subscribeNow on a list., Email Lists ,When sending a campaign to an email list, only subscribers that have a subscription with status subscribed will receive the campaign.

To ensure that all subscribers of your email list really wanted to subscribe, you can enable the double opt-in requirement.

EmailList::create([ 'name' => 'My list' 'requires_confirmation' => true, ]); 

When a person clicks the email confirmation link, a simple message explaining the result of confirmation is displayed. You can customize that response by publishing the views.

php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-views" 

First, you must publish the views.

php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-views" 

Источник

How to Build an Autoresponder – the Opt-in Form

If you’re new here, you may want to follow us on Facebook or Twitter. Thanks for visiting!

Thanks for coming back to visit. If you like what you’ve read, or if you don’t, then please leave me a comment below. Thanks!

How to create an email opt-in form in WordPress

I wrote last week about how I decided a while back to see if I could build my own opt-in email autoresponder system as a WordPress plugin. The first part that I chose to figure out was the double opt-in component, which I will describe here.

Before I get into that, I want to point out some potential limitations of building an email autoresponder into a WordPress plugin. I don’t think the actual opt-in process will be that significant because it is only handling traffic that is already on the website. It just involves sending an extra email message and and an extra page load as the visitor completes the double opt-in.

All of the opt-in data and scheduled emails will be stored in the WordPress database. This could become a performance issue as you add thousands (hopefully) of new contacts to the database.

Having WordPress handle sending broadcast emails to those thousands of subscribers will be a bigger issue. First is the actual processing load from sending thousands of emails. The second issue is the actual logistics of sending thousands of emails. Most personal email accounts limit the number of emails that can be sent in a period of time to discourage spamming.

This solution should work for a small list of up to a few hundred subscribers as long as there is a mechanism in place to space out the emails so that they are sent over a few hours, or possibly through a bulk email service. I haven’t looked into that yet.

As I said last time, my goal with this project is to learn about how email autoresponders work so that I can make the best use of one when I go back to an established service like Aweber or MailChimp.

One More Thing Before We Get Started

It isn’t my intent here to teach you how to write PHP code (the programming language that all of the WordPress scripts are written in) or all of the inner workings of WordPress. I more want to point you in the right direction to learn more if you want to.

The Opt-in System

Ok, on to the opt-in system. First, let’s take a look at the sequence of events that have to happen to get a subscriber completely opted in so that they can receive emails from us.

  1. Display a form on the page to capture the subscribers info
  2. Receive the form submission
  3. Validate the data, prevent multiple opt-ins
  4. Display a thank you page or error page as appropriate
  5. Send a confirmation email with a link for the subscriber to confirm the opt-in
  6. Process the subscriber clicking on the link from the confirmation email
  7. Display another thank you page once the subscriber is completely in

Display the Opt-in Form

For the actual form, I cheated. I copied the HTML and CSS from an old Aweber form that I had in the past and embedded it as a short code in my new plugin. I am more than happy to let someone else handle all of the intricacies of writing the CSS.

If you have used WordPress for awhile then you probably already know what a short code is. Just in case you don’t, I’ll explain it very briefly. A short code allows you to embed some piece of functionality into your post. For example, boxes like the one below for tweeting a message to Twitter have become popular.

A short code is written between square brackets and starts with the name of the short code followed by any attributes that it supports. You can see the entire short code that created the tweet box here:

[bctt tweet=»Have you read about this crazy guy who is writing his own email autoresponder?»]

This particular short code is named bctt and takes one attribute, tweet, which provides the message that you want your visitors to tweet. This short code is provided by the Better Click to Tweet plugin by Ben Meredith.

A short code seemed the easiest way to be able to display my opt-in form within my content, and writing a short code isn’t too hard.

The Pieces of a Short Code

The first part of creating a short code is the PHP function that will process the parameters and generate the content that will display in the finished post in place of the short code. The second piece is to inform WordPress about the short code so that it knows to call your function when it sees that short code in a post.

In this case, I designed my short code to look like this:

I named the short code ywoptin and it takes one attribute called campaign which specifies the name of the list campaign that the opt-in form is for, in this case it is my “test” campaign.

The PHP function declaration looks like this:

function ywoptin_shortcode( $atts, $content = null )

The name of the PHP function here is ywoptin_shortcode and WordPress requires short code functions to take two parameters: $atts is an array containing the attributes (campaign and its value, test) and $content is all of the content that is between the open and close tags for the short code. I don’t have any with my short code, so I set it to null.

If my short looked like this: [[ywoptin]do ray mi fa so la ti do[/ywoptin]] then $content would contain “do ray mi fa so la ti do.”

The function just contains the HTML to display the opt-in form and sets the campaign name as a hidden input field in the form. The final HTML is then returned to WordPress.

We now have to let WordPress know that when it sees a short code called ywoptin, it should call the ywoptin_shortcode function to handle it. We do this by calling the add_shortcode function, which is defined by WordPress. It looks like this:

It’s pretty self-explanatory. The first parameter is the name of the short code and the second parameter is the name of the function to be called.

Here’s what the opt-in form looks like so far. It will successfully add you to a list that I will use to notify you the next time I write a post in this series.

Next Time

That is enough to get the opt-in form to display. That was the easy part. We still have to do something with it once the subscriber clicks the button after they enter their name and email address. I struggled for awhile to figure out how to do that from a post or a page. I will go into that next time. I intend for that to be up next Thursday night or Friday morning.

If you missed the first part in this series, please read about why I’m taking on this project.

I would love to hear any thoughts you have on this little project of mine, even if it is just to call me crazy. Leave me a comment below, and I always appreciate it when you share my posts to your followers on social media.

Источник

Читайте также:  Где расположен python windows
Оцените статью