doutiaosu2310 2017-12-31 12:44
浏览 59
已采纳

Cron作业没有运行php脚本

I have created a cron job in my cpanel using command below:

/usr/bin/php -q /home/user/public_html/folder/subfolder/sync.php

The content of syns.php is almost like this. It works without error when I run it with the domain like domain.com/folder/subfolder/sync.php but I can not see the expected result when the cron job supposed to run which means cron job is not running the script. So can anyone tell me what might be the problem?

<?php

$dir = str_replace("public_html","", $_SERVER["DOCUMENT_ROOT"]);
$dir = $dir . "configuration.php";

if (file_exists($dir)) 
{
    require_once($dir);
    sync();
} 
else
{
    // echo ("Can't find the access data.");
}

function sync()
{
    $connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
    if(mysqli_connect_errno())
    {
        // echo ("Failed to connect the database.");
        exit();
    }
    else
    {
        if(mysqli_ping($connection))
        {
            $query = "SELECT OR UPDATE WHATEAVER FROM TABLE;";
            $result = mysqli_multi_query($connection, $query);
            if($result)
            {
                // Do stuff
            }
            else
            {
                // echo("Failed to excute the query.");
            }
        }
        else
        {
            // echo("Failed to ping the connection.");
        }
    }
    mysqli_close($connection);
}

?>
  • 写回答

1条回答 默认 最新

  • duanqin9631 2017-12-31 12:52
    关注

    $_SERVER['DOCUMENT_ROOT'] is created by your webserver (e.g. Apache) before calling PHP. If you're running your script via a cronjob, you're bypassing your webserver and the DOCUMENT_ROOT will not exist.

    You should determine the location of your configuration file in another way. One way is to use PHP's built-in constants for file locations, like __FILE__ or __DIR__:

    $dir = __DIR__ . "/configuration.php";
    

    __DIR__ refers to the folder containing the current file, so this will become /home/user/public_html/folder/subfolder/configuration.php.

    From what you're doing with $_SERVER['DOCUMENT_ROOT'] I assume your configuration file is one folder up from public_html, so you could do something like this:

    $dir = __DIR__ . "/../../../configuration.php";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵