html + php 手机验证码
时间: 2023-11-28 16:33:10 浏览: 42
生成手机验证码的方法可以分为两种:前端生成和后端生成。下面为您提供其中一种实现方法。
前端生成:
1. 在 HTML 页面中添加一个 input 标签,用于输入验证码。
```html
<input type="text" id="code" name="code" placeholder="请输入验证码" />
```
2. 在 PHP 中生成验证码,将其存储到 session 中,并返回给前端页面。
```php
session_start();
$code = rand(1000, 9999);
$_SESSION['code'] = $code;
echo $code;
```
3. 在 JavaScript 中监听 input 标签的 focus 事件,当用户点击输入框时,异步请求服务器获取验证码。
```javascript
document.querySelector('#code').addEventListener('focus', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'generate_code.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.querySelector('#code').value = xhr.responseText;
}
};
xhr.send();
});
```
后端生成:
1. 在 HTML 页面中添加一个 input 标签,用于输入验证码。
```html
<input type="text" id="code" name="code" placeholder="请输入验证码" />
```
2. 在 PHP 中生成验证码,并将其发送到用户手机。
```php
$code = rand(1000, 9999);
$mobile = '13888888888'; // 手机号码
$content = '您的验证码为:' . $code;
$url = 'http://www.api.com/sms/send'; // 短信发送接口
$data = array(
'mobile' => $mobile,
'content' => $content
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
echo '发送失败';
} else {
session_start();
$_SESSION['code'] = $code;
echo '发送成功';
}
```
3. 在 JavaScript 中监听 input 标签的 focus 事件,当用户点击输入框时,调用后端接口发送验证码。
```javascript
document.querySelector('#code').addEventListener('focus', function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'send_code.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send();
});
```
以上代码仅供参考,实际应用中还需要进行安全性验证和错误处理。