The approach works like this (#2 just recently added):
- I log-in to my admin section with a username and password (PHP script), which I have done for years.
- Now, a SMS code is sent to my phone number with an additional code needed to complete the log-in process.
This was super simple to setup using Twilio. I followed this guide from phpmaster.
Here is an example of how the code works. First, when you check that the standard log-in form is submitted (with the username and password), that is where we will place the Twilio code that sends a SMS message:
require "classes/twilio/Twilio.php"; define("TWILIO_SID", "YOUR SID HERE"); define("TWILIO_AUTH_TOKEN", "YOUR AUTH TOKEN HERE"); $twilio = new Services_Twilio(TWILIO_SID, TWILIO_AUTH_TOKEN); $acct = $twilio->account;
Above we establish an instance of the Twilio class using our authentication keys found on your Twilio dashboard page:
Next, let’s generate a random four-digit code in PHP:
$sms_code = rand(1000, 10000);
Make it a hash and save it to the session:
$_SESSION["auth_sms_code"] = md5($sms_code);
Now when we receive the SMS code on our phone and enter it into the site, it can be verified by looking at the session variable.
Send the SMS code:
$msg = $acct->sms_messages->create( "+11234567890", // FROM (Twilio account phone number) "+11234567890", // TO (message recipient) "Your access code is " . $sms_code );
Upon receiving the SMS code, and entering it into the site, we check that it matches the session variable:
if (md5($_POST["auth_sms_code"]) == $_SESSION["auth_sms_code"]) ...
If so, set another session variable that indicates a successful log-in. If they do not match, deny access until completely verified.
You could also do this with SMSified, but when I tested recently I was receiving some odd errors back, and it seems Twilio has a more polished (and recently updated) product.