In continuation with my previous blog Creating-Rest-API-to-generate-otp-part-1, this post covers the rest of the procedure to generate the OTP and exposes the two PHP endpoints used: requestsms.php and verifyotp.php.
Prerequisites
- Working LAMP/LEMP stack with PHP and cURL enabled.
- include/DbHandler.php present in your project root. The article assumes DbHandler provides functions invoked below (createUser() and activateUser()).
- Constants defined somewhere safe (not committed to source): MSG91AUTHKEY and MSG91SENDERID. Prefer environment variables or a protected config file.
- Database tables:
Usersandsms_codes(see Part 1 for full schema). The code below expects the createUser(…) and activateUser(…) methods in DbHandler to manage rows and statuses.
What this part covers
- Creating the
request_sms.phpendpoint that receives name, email, mobile via POST, creates a user row (initially inactive), generates a 6-digit OTP, saves it and requests an SMS via MSG91. - Creating the
verify_otp.phpendpoint that receives an OTP via POST, matches the user, and activates the user (sets status to 1 in users and sms_codes table).
Notes: The examples below are the original code as used in my test project. I kept the code intact but added security and implementation notes in the sections that follow. Before deploying to production, apply the security improvements listed earlier in this article.
request_sms.php (endpoint to register user and request OTP)
The endpoint receives name, email, and mobile as POST parameters, creates a user with status 0 (inactive) via createUser() in DbHandler, then calls sendSms() which connects to MSG91 REST API and sends a 6-digit OTP.
Below is the code used in request_sms.php:
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Welcome to Tech Thoughts. Your OTP is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => MSG91_AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => MSG91_SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.msg91.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification (demo only) - do NOT use in production
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
Notes and improvements for request_sms.php
- OTP generation: Use random_int(100000, 999999) (PHP7+) instead of rand(), and implement OTP expiry (timestamp) and attempt counters in the DB.
- Credentials: Do not hardcode MSG91AUTHKEY and MSG91SENDERID. Use environment variables or a server-side protected config file that is not committed.
- SSL verification: The example disables SSL verification for demo. In production, remove CURLOPTSSLVERIFYHOST/PEER settings and trust the provider's certificate or provide CA bundle path.
- Input validation: Validate
mobileformat and sanitizenameandemail. Ensure DbHandler uses prepared statements to avoid SQL injection. - Response structure: Consider sending HTTP status codes (400 for bad request, 201 for created, 500 for server errors) in addition to JSON.
- Rate limiting: Implement per-mobile rate limiting to avoid SMS abuse.
Sample outgoing SMS message
Below is the sample SMS message the user will receive to their mobile. The OTP should be prefixed by ":" and space in the message.
"Welcome to Tech Thoughts. Your OTP is : 217798"
verify_otp.php (endpoint to verify OTP)
This endpoint receives otp as a POST parameter, calls activateUser() in DbHandler which should find the matching user and set status to 1 in users and sms_codes table. If the OTP matches and activation succeeds, the complete user profile is returned.
Below is the code used in verify_otp.php:
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
$response["error"] = false;
if (isset($_POST['otp']) && $_POST['otp'] != '') {
$otp = $_POST['otp'];
$user = $db->activateUser($otp);
if ($user != NULL) {
$response["message"] = "User created successfully!";
$response["profile"] = $user;
} else {
$response["message"] = "Sorry! Failed to create your account.";
}
} else {
$response["message"] = "Sorry! OTP is missing.";
}
echo json_encode($response);
?>
Notes and improvements for verify_otp.php
- Brute-force protection: Implement rate limiting on OTP verification attempts per mobile/IP and consider increasing lockout after N failed attempts.
- OTP expiry: Verify that the OTP hasn't expired (store expiration timestamp in
sms_codes). - Secure responses: Return clear error codes and appropriate HTTP status codes.
- Atomic activation: Ensure activateUser updates both users and sms_codes in a transaction to avoid inconsistent state.
API testing and download
Now you can test this REST API using Postman (Chrome extension) or use the sample PHP pages supplied in the download. I created two small test files in the sample zip: index.php (collects name, email, mobile and calls requestsms.php) and another verification page (calls verifyotp.php).
Request examples (endpoints)
Request SMS
- URL: http://localhost/android_sms/request_sms.php
- Method: POST
- Parameters: name, email, mobile
- Description: Request SMS
The below JSON is produced when SMS is queued successfully:
{
"error": false,
"message": "SMS request is initiated! You will be receiving it shortly."
}
Verifying user OTP
- URL: http://localhost/android_sms/verify_otp.php
- Method: POST
- Parameters: otp
- Description: verifying user verification code
When the OTP is verified successfully, the full user profile is produced in JSON (example):
{
"error": false,
"message": "User created successfully!",
"profile": {
"name": "G T Karjol",
"email": "karjol@gmail.com",
"mobile": "0000000000",
"apikey": "4a6ed225209632e5467b237c6b00d310",
"status": 0,
"created_at": "2016-01-27 15:12:22"
}
}
Security and production checklist (summary)
- Move MSG91 credentials to environment variables (e.g., $_ENV or getenv()).
- Use randomint() for OTP, store a createdat and expires_at, and hash OTPs if you want to avoid plain-text storage.
- Re-enable SSL verification and validate provider certificate.
- Use prepared statements in DbHandler and validate all inputs server-side.
- Implement rate limiting and lockouts on repeated requests and verification attempts.
- Use HTTPS for the API endpoints and ensure CORS and authentication policies are appropriate for your clients.
Troubleshooting and next steps
- If SMS delivery fails, inspect the $output returned by the MSG91 API call and log it to a secure file. Do not echo or expose raw API responses or credentials in production logs.
- Verify that
include/DbHandler.phpimplements the expected return codes: USERCREATEDSUCCESSFULLY, USERCREATEFAILED, USERALREADYEXISTED, and that activateUser($otp) returns the full user profile on success. - Consider adding an audit table for OTP sends and verification attempts to support analytics and abuse detection.
References and downloads
- Part 1: Creating-Rest-API-to-generate-otp-part-1 — http://karjol-gt.blogspot.in/2016/01/creating-rest-api-to-generate-otp-part-1.html
- Download full sample code (index.php test client + verify page): https://sites.google.com/site/karjolblogs/downloads/OTP_SMS.zip?attredirects=0&d=1
That's it. Happy Coding.
No comments:
Post a Comment