Appearance
第 17 章:常用功能开发
17.1 发送邮件
使用 PHP 内置 mail() 函数
php
<?php
$to = "recipient@example.com";
$subject = "测试邮件";
$message = "这是一封测试邮件";
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "邮件发送成功";
} else {
echo "邮件发送失败";
}
?>使用 PHPMailer(推荐)
php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// 服务器配置
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// 收发件人
$mail->setFrom('from@example.com', '发件人名称');
$mail->addAddress('to@example.com', '收件人名称');
// 内容
$mail->isHTML(true);
$mail->Subject = '测试邮件';
$mail->Body = '<h1>这是一封测试邮件</h1><p>邮件内容</p>';
$mail->AltBody = '这是纯文本内容';
$mail->send();
echo '邮件发送成功';
} catch (Exception $e) {
echo "邮件发送失败: {$mail->ErrorInfo}";
}
?>17.2 验证码
生成验证码图片
php
<?php
session_start();
// 生成验证码
$code = '';
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
// 存储到 session
$_SESSION['captcha'] = $code;
// 创建图片
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
// 设置颜色
$bg_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
// 填充背景
imagefill($image, 0, 0, $bg_color);
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$line_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);
}
// 添加文字
imagestring($image, 5, 20, 7, $code, $text_color);
// 输出图片
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>验证验证码
php
<?php
session_start();
if (isset($_POST['captcha'])) {
if (strtolower($_POST['captcha']) === strtolower($_SESSION['captcha'])) {
echo "验证码正确";
} else {
echo "验证码错误";
}
}
?>
<!-- HTML 表单 -->
<form method="post">
<img src="captcha.php" alt="验证码"><br>
<input type="text" name="captcha" placeholder="请输入验证码"><br>
<button type="submit">提交</button>
</form>17.3 分页功能
分页实现
php
<?php
// 连接数据库
$conn = mysqli_connect("localhost", "root", "", "myDB");
// 每页显示数量
$per_page = 10;
// 当前页码
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
// 计算偏移量
$offset = ($page - 1) * $per_page;
// 查询总记录数
$sql = "SELECT COUNT(*) as total FROM articles";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$total = $row['total'];
// 计算总页数
$total_pages = ceil($total / $per_page);
// 查询当前页数据
$sql = "SELECT * FROM articles LIMIT $offset, $per_page";
$result = mysqli_query($conn, $sql);
// 显示数据
while ($row = mysqli_fetch_assoc($result)) {
echo $row['title'] . '<br>';
}
// 显示分页链接
echo '<div class="pagination">';
if ($page > 1) {
echo '<a href="?page=' . ($page - 1) . '">上一页</a>';
}
for ($i = 1; $i <= $total_pages; $i++) {
if ($i == $page) {
echo '<span>' . $i . '</span>';
} else {
echo '<a href="?page=' . $i . '">' . $i . '</a>';
}
}
if ($page < $total_pages) {
echo '<a href="?page=' . ($page + 1) . '">下一页</a>';
}
echo '</div>';
mysqli_close($conn);
?>分页函数封装
php
<?php
function paginate($total, $per_page, $current_page, $url) {
$total_pages = ceil($total / $per_page);
$html = '<div class="pagination">';
// 上一页
if ($current_page > 1) {
$html .= '<a href="' . $url . '?page=' . ($current_page - 1) . '">上一页</a>';
}
// 页码
$start = max(1, $current_page - 2);
$end = min($total_pages, $current_page + 2);
if ($start > 1) {
$html .= '<a href="' . $url . '?page=1">1</a>';
if ($start > 2) {
$html .= '<span>...</span>';
}
}
for ($i = $start; $i <= $end; $i++) {
if ($i == $current_page) {
$html .= '<span class="current">' . $i . '</span>';
} else {
$html .= '<a href="' . $url . '?page=' . $i . '">' . $i . '</a>';
}
}
if ($end < $total_pages) {
if ($end < $total_pages - 1) {
$html .= '<span>...</span>';
}
$html .= '<a href="' . $url . '?page=' . $total_pages . '">' . $total_pages . '</a>';
}
// 下一页
if ($current_page < $total_pages) {
$html .= '<a href="' . $url . '?page=' . ($current_page + 1) . '">下一页</a>';
}
$html .= '</div>';
return $html;
}
// 使用
echo paginate(100, 10, 5, 'articles.php');
?>17.4 接口开发(返回 JSON)
创建 API 接口
php
<?php
header('Content-Type: application/json; charset=utf-8');
// 连接数据库
$conn = mysqli_connect("localhost", "root", "", "myDB");
// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];
// 获取请求数据
$input = json_decode(file_get_contents('php://input'), true);
switch ($method) {
case 'GET':
// 查询数据
$sql = "SELECT * FROM articles";
$result = mysqli_query($conn, $sql);
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode([
'code' => 200,
'message' => 'success',
'data' => $data
]);
break;
case 'POST':
// 添加数据
$title = mysqli_real_escape_string($conn, $input['title']);
$content = mysqli_real_escape_string($conn, $input['content']);
$sql = "INSERT INTO articles (title, content) VALUES ('$title', '$content')";
if (mysqli_query($conn, $sql)) {
echo json_encode([
'code' => 200,
'message' => '添加成功',
'data' => ['id' => mysqli_insert_id($conn)]
]);
} else {
echo json_encode([
'code' => 500,
'message' => '添加失败'
]);
}
break;
case 'PUT':
// 更新数据
$id = (int)$input['id'];
$title = mysqli_real_escape_string($conn, $input['title']);
$content = mysqli_real_escape_string($conn, $input['content']);
$sql = "UPDATE articles SET title = '$title', content = '$content' WHERE id = $id";
if (mysqli_query($conn, $sql)) {
echo json_encode([
'code' => 200,
'message' => '更新成功'
]);
} else {
echo json_encode([
'code' => 500,
'message' => '更新失败'
]);
}
break;
case 'DELETE':
// 删除数据
$id = (int)$_GET['id'];
$sql = "DELETE FROM articles WHERE id = $id";
if (mysqli_query($conn, $sql)) {
echo json_encode([
'code' => 200,
'message' => '删除成功'
]);
} else {
echo json_encode([
'code' => 500,
'message' => '删除失败'
]);
}
break;
default:
echo json_encode([
'code' => 405,
'message' => '不支持的请求方法'
]);
}
mysqli_close($conn);
?>17.5 AJAX 交互(无刷新)
前端 AJAX 请求
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX 示例</title>
<script>
// 原生 JavaScript AJAX
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'api.php', true);
xhr.onload = function() {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
console.log(data);
// 更新页面
var html = '';
data.data.forEach(function(item) {
html += '<div>' + item.title + '</div>';
});
document.getElementById('result').innerHTML = html;
}
};
xhr.send();
}
// jQuery AJAX
function loadDataJQuery() {
$.ajax({
url: 'api.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
// 更新页面
var html = '';
data.data.forEach(function(item) {
html += '<div>' + item.title + '</div>';
});
$('#result').html(html);
},
error: function(xhr, status, error) {
console.error(error);
}
});
}
// Fetch API
function loadDataFetch() {
fetch('api.php')
.then(response => response.json())
.then(data => {
console.log(data);
// 更新页面
let html = '';
data.data.forEach(item => {
html += '<div>' + item.title + '</div>';
});
document.getElementById('result').innerHTML = html;
})
.catch(error => console.error(error));
}
</script>
</head>
<body>
<button onclick="loadData()">加载数据</button>
<div id="result"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>后端处理 AJAX 请求
php
<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');
// 连接数据库
$conn = mysqli_connect("localhost", "root", "", "myDB");
// 处理 GET 请求
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$sql = "SELECT * FROM articles";
$result = mysqli_query($conn, $sql);
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode([
'code' => 200,
'message' => 'success',
'data' => $data
]);
}
// 处理 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
$title = mysqli_real_escape_string($conn, $input['title']);
$content = mysqli_real_escape_string($conn, $input['content']);
$sql = "INSERT INTO articles (title, content) VALUES ('$title', '$content')";
if (mysqli_query($conn, $sql)) {
echo json_encode([
'code' => 200,
'message' => '添加成功'
]);
} else {
echo json_encode([
'code' => 500,
'message' => '添加失败'
]);
}
}
mysqli_close($conn);
?>小结
通过本章的学习,你掌握了 PHP 开发中常用的功能实现,包括发送邮件、生成验证码、分页功能、API 接口开发和 AJAX 交互。这些功能在 Web 开发中非常常见,掌握它们的实现方法对于开发完整的 Web 应用非常重要。在实际开发中,你可以根据项目需求选择合适的实现方式,并注意安全性和性能优化。
