php实现重发
PHP 实现重发功能
重发功能通常用于表单提交失败后重新发送数据,或者在HTTP请求失败时重新尝试发送请求。以下是几种常见的实现方法:
表单重发
使用PHP的会话机制保存表单数据,在页面刷新时自动填充:

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['form_data'] = $_POST;
// 处理表单数据...
unset($_SESSION['form_data']); // 处理完成后清除
}
?>
<form method="post">
<input type="text" name="username" value="<?php echo isset($_SESSION['form_data']['username']) ? htmlspecialchars($_SESSION['form_data']['username']) : ''; ?>">
<!-- 其他表单字段 -->
<button type="submit">提交</button>
</form>
HTTP请求重试
对于API请求,可以实现自动重试机制:

function sendRequestWithRetry($url, $data, $maxRetries = 3) {
$retryCount = 0;
while ($retryCount < $maxRetries) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 300) {
return $response;
}
$retryCount++;
sleep(1); // 等待1秒后重试
}
return false;
}
邮件重发
实现邮件发送失败后的重发功能:
function resendEmail($to, $subject, $message, $maxAttempts = 3) {
$attempt = 0;
$sent = false;
while (!$sent && $attempt < $maxAttempts) {
$sent = mail($to, $subject, $message);
if (!$sent) {
$attempt++;
sleep(2); // 等待2秒后重试
}
}
return $sent;
}
数据库操作重试
对于可能失败的数据库操作:
function executeQueryWithRetry($query, $connection, $maxRetries = 3) {
$retryCount = 0;
$success = false;
while (!$success && $retryCount < $maxRetries) {
try {
$result = mysqli_query($connection, $query);
$success = true;
return $result;
} catch (Exception $e) {
$retryCount++;
sleep(1);
}
}
return false;
}
注意事项
- 重试机制应设置最大尝试次数,避免无限循环
- 重试之间应有适当的间隔时间
- 对于表单重发,务必对输出数据进行转义,防止XSS攻击
- 记录失败日志,便于排查问题
- 对于关键操作,考虑实现队列系统而不是即时重试






