You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在网站无人访问/离线时执行PHP脚本?

问题:网页关闭后停止生成随机数并写入MySQL数据库

我正在开发一个简单网页,功能为生成随机数并将其写入MySQL数据库,该脚本参考网络上各位用户的解答与帮助实现,在此致谢。目前功能正常,但存在一个问题:仅在网页打开时会生成随机数并写入数据库,关闭网页后便停止运行。我已多方搜索但未找到符合需求的解决方案,以下是我使用的代码:

<?php

include_once 'database.php';

if ($conn) {
    echo "success<br>";
}

$digits = 3;

$result = rand(pow(10, $digits-1), pow(10, $digits)-1);
//this is sum
$num = $result;  
$sum=0;
$rem=0;  
  for ($i =0; $i<=strlen($num);$i++)  
 {  
    $rem=$num%10;  
    $sum = $sum + $rem;  
    $num=$num/10;  
    $total = substr($sum, -1);
     
 }  
 
 //echo "Sum of digits $result is $sum"; 

$finres = $result.'-'.$total;
// $result = mysql_real_escape_string($result);
// $total = mysql_real_escape_string($total);


// while( $digits = 3 )
// {
//     echo $result;
//    sleep(10);
// }

?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="refresh" content="5" > 
    <title>Ghanta Bazar</title>
</head>
<body>

<p><?php echo $finres; ?></p>
<?php 

$sql = "INSERT INTO ghanta_result (result)
VALUES ($finres)";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}


?>
    
</body>
</html>
解决方案

你的代码依赖浏览器访问触发执行,关闭网页后自然停止运行。要实现后台持续生成并写入数据,有两种可行方案:

方案一:服务器定时任务(Cron Job)

这是最稳定常用的方式,让服务器定期执行生成逻辑:

  1. 拆分代码:把生成、计算、写入数据库的逻辑单独提取为后台脚本(比如generate_and_save.php),移除HTML部分:
<?php
include_once 'database.php';

if (!$conn) {
    exit("数据库连接失败");
}

$digits = 3;
$result = rand(pow(10, $digits-1), pow(10, $digits)-1);

// 计算数字和的最后一位
$num = $result;  
$sum = 0;
while ($num > 0) {  
    $rem = $num % 10;  
    $sum += $rem;  
    $num = (int)($num / 10);  
}  
$total = substr($sum, -1);

$finres = $result . '-' . $total;

// 用预处理语句防止SQL注入
$sql = "INSERT INTO ghanta_result (result) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $finres);

if ($stmt->execute()) {
    // 写入日志记录执行状态
    file_put_contents('cron_log.txt', date('Y-m-d H:i:s') . " 记录写入成功: $finres\n", FILE_APPEND);
} else {
    file_put_contents('cron_log.txt', date('Y-m-d H:i:s') . " 写入失败: " . $stmt->error . "\n", FILE_APPEND);
}

$stmt->close();
$conn->close();
?>
  1. 设置Cron任务:在Linux服务器终端执行crontab -e编辑定时任务,添加以下内容(示例为每5分钟执行一次):
*/5 * * * * /usr/bin/php /path/to/your/generate_and_save.php
  • */5 * * * *:执行频率,可按需调整(比如* * * * *为每分钟一次)
  • /usr/bin/php:PHP执行路径,可通过which php查看实际路径
  • /path/to/your/generate_and_save.php:脚本的绝对路径

方案二:后台长期运行脚本

如果需要持续不间断执行(而非定时间隔),可编写无限循环脚本并后台运行:

  1. 编写后台脚本(比如continuous_generator.php):
<?php
include_once 'database.php';

if (!$conn) {
    exit("数据库连接失败");
}

// 设置脚本不超时,忽略用户中断
set_time_limit(0);
ignore_user_abort(true);

while (true) {
    $digits = 3;
    $result = rand(pow(10, $digits-1), pow(10, $digits)-1);

    // 计算数字和的最后一位
    $num = $result;  
    $sum = 0;
    while ($num > 0) {  
        $rem = $num % 10;  
        $sum += $rem;  
        $num = (int)($num / 10);  
    }  
    $total = substr($sum, -1);

    $finres = $result . '-' . $total;

    // 用预处理语句防止SQL注入
    $sql = "INSERT INTO ghanta_result (result) VALUES (?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $finres);

    if ($stmt->execute()) {
        file_put_contents('continuous_log.txt', date('Y-m-d H:i:s') . " 记录写入成功: $finres\n", FILE_APPEND);
    } else {
        file_put_contents('continuous_log.txt', date('Y-m-d H:i:s') . " 写入失败: " . $stmt->error . "\n", FILE_APPEND);
    }

    $stmt->close();
    // 间隔5秒执行一次,可调整
    sleep(5);
}

$conn->close();
?>
  1. 后台启动脚本:在服务器终端执行以下命令,让脚本脱离终端持续运行:
nohup php continuous_generator.php > /dev/null 2>&1 &
  • 若要停止脚本,可通过ps aux | grep continuous_generator.php找到进程ID,再用kill 进程ID终止

重要注意事项

  • SQL注入防护:原代码直接拼接变量到SQL语句,存在严重安全风险,解决方案中使用了预处理语句修复此问题,务必保留。
  • 日志记录:后台执行的脚本无终端输出,添加日志可方便排查问题。
  • 资源控制:长期运行的脚本要合理设置执行间隔,避免过度消耗服务器CPU或数据库资源。

内容的提问来源于stack exchange,提问作者Nilesh Singh Dahiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:35:54