php數據驗證 + 過濾 + 參數綁定
絕對不建議直接操作 $_POST! 這是一個非常重要的安全實踐。
? 為什么不建議直接使用 $_POST
直接使用 $_POST 的問題:
// ? 危險做法 - 千萬不要這樣寫!
$sql = "INSERT INTO users (username, email) VALUES ('{$_POST['username']}', '{$_POST['email']}')";
// SQL注入漏洞!
? 推薦的最佳實踐
1. 數據驗證 + 過濾 + 參數綁定
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 方法一:從 $_POST 獲取(表單格式)
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
// 方法二:從 JSON 獲取(推薦用于 Vue/Ajax)
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$username = $input['username'] ?? '';
$email = $input['email'] ?? '';
// 1. 數據驗證
$errors = [];
if (empty($username) || strlen($username) < 2) {
$errors[] = '用戶名至少2個字符';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = '郵箱格式不正確';
}
if (!empty($errors)) {
http_response_code(400);
echo json_encode(['success' => false, 'errors' => $errors]);
exit;
}
// 2. 數據清理
$username = trim($username);
$username = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// 3. 創建數據數組
$data = [
'username' => $username,
'email' => $email,
'created_at' => date('Y-m-d H:i:s'),
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? ''
];
// 4. 插入數據庫(使用預處理語句)
try {
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("INSERT INTO users (username, email, created_at, ip_address) VALUES (:username, :email, :created_at, :ip_address)");
$stmt->execute([
':username' => $data['username'],
':email' => $data['email'],
':created_at' => $data['created_at'],
':ip_address' => $data['ip_address']
]);
echo json_encode(['success' => true, 'message' => '數據插入成功', 'id' => $pdo->lastInsertId()]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => '數據庫錯誤: ' . $e->getMessage()]);
}
}
?>
2. 使用封裝的數據處理類
<?php
class DataProcessor {
public static function getJsonInput() {
$input = json_decode(file_get_contents('php://input'), true);
return is_array($input) ? $input : [];
}
public static function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public static function sanitizeString($string, $maxLength = 255) {
$string = trim($string);
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
return substr($string, 0, $maxLength);
}
public static function validateRequired($data, $fields) {
$errors = [];
foreach ($fields as $field) {
if (empty($data[$field])) {
$errors[] = "{$field} 是必填字段";
}
}
return $errors;
}
}
// 使用示例
$input = DataProcessor::getJsonInput();
$requiredFields = ['username', 'email'];
$validationErrors = DataProcessor::validateRequired($input, $requiredFields);
if (!empty($validationErrors)) {
http_response_code(400);
echo json_encode(['success' => false, 'errors' => $validationErrors]);
exit;
}
// 清理數據
$cleanData = [
'username' => DataProcessor::sanitizeString($input['username']),
'email' => filter_var($input['email'], FILTER_SANITIZE_EMAIL),
];
if (!DataProcessor::validateEmail($cleanData['email'])) {
echo json_encode(['success' => false, 'errors' => ['郵箱格式無效']]);
exit;
}
// 然后執行數據庫操作...
?>
3. 完整的郵件發送數據處理示例
<?php
// send-email.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 獲取并驗證數據
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$emailData = [
'to' => filter_var($input['to'] ?? '', FILTER_SANITIZE_EMAIL),
'subject' => htmlspecialchars($input['subject'] ?? '', ENT_QUOTES, 'UTF-8'),
'content' => htmlspecialchars($input['content'] ?? '', ENT_QUOTES, 'UTF-8'),
'created_at' => date('Y-m-d H:i:s')
];
// 驗證
if (!filter_var($emailData['to'], FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => '收件人郵箱格式錯誤']);
exit;
}
if (empty($emailData['subject']) || empty($emailData['content'])) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => '郵件主題和內容不能為空']);
exit;
}
try {
// 先保存到數據庫
$pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8mb4', 'user', 'pass');
$stmt = $pdo->prepare("INSERT INTO email_logs (to_email, subject, content, created_at) VALUES (:to, :subject, :content, :created_at)");
$stmt->execute($emailData);
// 然后發送郵件
$mailSent = mail(
$emailData['to'],
$emailData['subject'],
$emailData['content'],
"From: no-reply@yoursite.com\r\nContent-Type: text/html; charset=UTF-8"
);
if ($mailSent) {
echo json_encode(['success' => true, 'message' => '郵件發送成功']);
} else {
echo json_encode(['success' => false, 'message' => '郵件發送失敗']);
}
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => '服務器錯誤: ' . $e->getMessage()]);
}
}
?>
??? 安全最佳實踐總結
- 永遠不要信任用戶輸入
- 始終進行數據驗證和過濾
- 使用預處理語句防止SQL注入
- 創建清理后的數據數組再操作數據庫
- 對輸出進行編碼防止XSS
- 使用合適的HTTP狀態碼
這樣的做法既安全又易于維護,是專業的PHP開發標準。

浙公網安備 33010602011771號