


Use laravel sms to build the function of sending SMS verification code for verification
This article introduces to you the use of laravel-sms to build an SMS verification code sending verification module through sample code. It is very good and has reference value. Friends in need can refer to
laravel to implement the SMS verification code function. , Searching for information, I found two popular packages:
One is laravel sms address https://github.com/toplan/laravel-sms
One is The address of easy sms is https://github.com/overtrue/easy-sms. The
project needs to implement a function of sending and verifying SMS verification codes. The previous method was a bit cumbersome. After advice from experts, I found that the laravel-sms package can be used instead. It is easy to configure and use. Hence this example.
This example uses Laravel 5.5, Api Starter Kit and Laravel Sms 2.6.
The SMS service provider used in this example is Yunpian.
Installation
Execute in the project root directory (recommended):
composer require toplan/laravel-sms:~2.6 composer require toplan/laravel-sms:~2.6
You can also add in the require field of composer.json:
"toplan/laravel-sms": "2.6" "toplan/laravel-sms": "2.6"
and then execute it in the project root directory:
composer update composer update
Add in the providers array of config/app.php:
Toplan\PhpSms\PhpSmsServiceProvider::class, Toplan\Sms\SmsManagerServiceProvider::class, Toplan\PhpSms\PhpSmsServiceProvider::class, Toplan\Sms\SmsManagerServiceProvider::class,
and add in the aliases array:
'PhpSms' => Toplan\PhpSms\Facades\Sms::class, 'SmsManager' => Toplan\Sms\Facades\SmsManager::class, 'PhpSms' => Toplan\PhpSms\Facades\Sms::class, 'SmsManager' => Toplan\Sms\Facades\SmsManager::class,
Execute in the project root directory:
php artisan vendor:publish --provider="Toplan\PhpSms\PhpSmsServiceProvider" php artisan vendor:publish --provider="Toplan\Sms\SmsManagerServiceProvider" php artisan vendor:publish --provider="Toplan\PhpSms\PhpSmsServiceProvider" php artisan vendor:publish --provider="Toplan\Sms\SmsManagerServiceProvider"
will be in the config folder Two configuration files are generated: phpsms.php and laravel-sms.php.
You can configure proxy information and balanced scheduling plan in phpsms.php.
The verification code sending and verification scheme can be configured in laravel-sms.php.
At the same time, the 2015_12_21_111514_create_sms_table.php file will be copied to database\migrations. Used to generate laravel_sms table.
Configuration
Here we only take cloud slices as an example.
Configure phpsms.php
Set the proxy information of the cloud slice in the agnets array in phpsms.php.
'YunPian' => [ //用户唯一标识,必须 'apikey' => '在这里填写你的 APIKEY', ], 'YunPian' => [ //用户唯一标识,必须 'apikey' => '在这里填写你的 APIKEY', ],
Set the scheme array and configure the balanced scheduling scheme.
'scheme' => [ 'YunPian', ], 'scheme' => [ 'YunPian', ],
Configure laravel-sms.php
Set built-in routing.
'route' => [ 'enable' => true, 'prefix' => 'laravel-sms', 'middleware' => ['api'], ], 'route' => [ 'enable' => true, 'prefix' => 'laravel-sms', 'middleware' => ['api'], ],
Set the request interval in seconds.
'interval' => 60, 'interval' => 60,
Set number verification rules.
'validation' => [ 'phone_number' => [ //需验证的字段 'isMobile' => true, //本字段是否为手机号 'enable' => true, //是否需要验证 'default' => 'mobile_required', //默认的静态规则 'staticRules' => [ //全部静态规则 'mobile_required' => 'required|zh_mobile', ], ], ], 'validation' => [ 'phone_number' => [ //需验证的字段 'isMobile' => true, //本字段是否为手机号 'enable' => true, //是否需要验证 'default' => 'mobile_required', //默认的静态规则 'staticRules' => [ //全部静态规则 'mobile_required' => 'required|zh_mobile', ], ], ],
Set verification code rules.
'code' => [ 'length' => 4, //验证码长度 'validMinutes' => 10, //验证码有效时间长度,单位为分钟 'repeatIfValid' => true, //验证码有效期内是否重复使用 'maxAttempts' => 0, //验证码最大尝试验证次数,0 或负数则不启用 ], 'code' => [ 'length' => 4, //验证码长度 'validMinutes' => 10, //验证码有效时间长度,单位为分钟 'repeatIfValid' => true, //验证码有效期内是否重复使用 'maxAttempts' => 0, //验证码最大尝试验证次数,0 或负数则不启用 ],
Set verification code content SMS.
'content' => function ($code, $minutes, $input) { return "您的验证码是:{$code} ({$minutes}分钟内有效,如非本人操作,请忽略)"; }, 'content' => function ($code, $minutes, $input) { return "您的验证码是:{$code} ({$minutes}分钟内有效,如非本人操作,请忽略)"; },
If necessary, you can enable database logging. You need to run php artisan migrate in advance to generate the laravel_sms table.
'dbLogs' => 'ture', 'dbLogs' => 'ture',
API implementation
Create a new SmsCodeUtil.php under app/Utils, and Implement the verification code sending and verification functions inside. In this way, other classes can be called at any time, improving code reusability.
Sending module
The mobile phone number needs to be verified before sending, including:
validateSendable() :验证是否满足发送间隔 validateFields() :验证数据合法性
After passing the verification, use requestVerifySms() to send the verification code.
The specific code is as follows:
use SmsManager; trait SmsCodeUtil { public function sendSmsCode() { $result = SmsManager::validateSendable(); if(!$result['success']) { return respondUnprocessable($result['message']); } $result = SmsManager::validateFields(); if(!$result['success']) { return respondUnprocessable($result['message']); } $result = SmsManager::requestVerifySms(); if(!$result['success']) { return respondUnprocessable($result['message']); } return respondSuccess($result['message']); } } use SmsManager; trait SmsCodeUtil { public function sendSmsCode() { $result = SmsManager::validateSendable(); if(!$result['success']) { return respondUnprocessable($result['message']); } $result = SmsManager::validateFields(); if(!$result['success']) { return respondUnprocessable($result['message']); } $result = SmsManager::requestVerifySms(); if(!$result['success']) { return respondUnprocessable($result['message']); } return respondSuccess($result['message']); } }
##Verification module
When logging in, you may need to verify your mobile phone number and verification code. Therefore, the verification code verification function needs to be added to SmsCodeUtil.php. The code has been given on the official Github here and can be modified slightly.public function validateSmsCode() { //验证数据 $validator = Validator::make(inputAll(), [ 'phone_number' => 'required|confirm_mobile_not_change|confirm_rule:mobile_required', 'sms_code' => 'required|verify_code', ]); if ($validator->fails()) { //验证失败后建议清空存储的发送状态,防止用户重复试错 SmsManager::forgetState(); respondUnprocessable(formatValidationErrors($validator)); } } public function validateSmsCode() { //验证数据 $validator = Validator::make(inputAll(), [ 'phone_number' => 'required|confirm_mobile_not_change|confirm_rule:mobile_required', 'sms_code' => 'required|verify_code', ]); if ($validator->fails()) { //验证失败后建议清空存储的发送状态,防止用户重复试错 SmsManager::forgetState(); respondUnprocessable(formatValidationErrors($validator)); } }
Functional Test
Next configure the routing and controller, Test whether the function is normal. You can openhost-domain/laravel-sms/info at the same time to view the verification code SMS sending and verification status.
$api->post('/auth/send-sms-code', 'Auth\LoginController@sendSmsCode'); $api->post('/auth/validate-sms-code', 'Auth\LoginController@validateSmsCode'); $api->post('/auth/send-sms-code', 'Auth\LoginController@sendSmsCode'); $api->post('/auth/validate-sms-code', 'Auth\LoginController@validateSmsCode');Then add in LoginController.php:
use App\Utils\SmsCodeUtil; class LoginController extends Controller { use SmsCodeUtil; ... } use App\Utils\SmsCodeUtil; class LoginController extends Controller { use SmsCodeUtil; ... }Then use Postman or other similar tools to test the Api functionality.
Send verification code
POST 服务器地址/api/auth/send-sms-code { "phone_number": "手机号" } POST 服务器地址/api/auth/send-sms-code { "phone_number": "手机号" }If the verification code is passed and sent successfully, It will return:
{ "message": "短信验证码发送成功,请注意查收", "status_code": 200 } { "message": "短信验证码发送成功,请注意查收", "status_code": 200 }The phone number filled in at the same time will receive the verification code. If the verification fails or the sending fails, the corresponding error message will be returned.
Verification verification code
POST 服务器地址/api/auth/validate-sms-code { "phone_number": "手机号", "sms_code": "验证码" } POST 服务器地址/api/auth/validate-sms-code { "phone_number": "手机号", "sms_code": "验证码" }If the verification is passed, then there is no return. If the verification fails, the corresponding error message will be returned. Localized prompt information language provides customization of some prompt information in laravel-sms.php. If you want to convert the remaining prompt information into the local language, you need to handle it separately. First make sure the language setting in config/app.php is correct. This is set to zh_cn.
'locale' => 'zh_cn', 'locale' => 'zh_cn',
然后在 resources\lang\zh_cn 文件夹下新建 validation.php,并填入本地化信息:
return [ 'required' => '缺少:attribute参数', 'zh_mobile' => '非标准的中国大陆手机号', 'confirm_mobile_not_change' => '提交的手机号已变更', 'verify_code' => '验证码不合法或无效', 'attributes' => [ 'phone_number' => '手机号', 'sms_code' => '验证码', ], ]; return [ 'required' => '缺少:attribute参数', 'zh_mobile' => '非标准的中国大陆手机号', 'confirm_mobile_not_change' => '提交的手机号已变更', 'verify_code' => '验证码不合法或无效', 'attributes' => [ 'phone_number' => '手机号', 'sms_code' => '验证码', ], ];
重新 POST 相关地址,可以看到对应的提示信息语言已经本地化。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
Laravel5.2使用Captcha生成验证码实现登录的方法
The above is the detailed content of Use laravel sms to build the function of sending SMS verification code for verification. For more information, please follow other related articles on the PHP Chinese website!

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
