简体   繁体   English

如何在 cron 中运行 php 脚本

[英]How to run a php script in cron

I have found many questions and articles about this but i still have some difficulties.我发现了很多关于这个的问题和文章,但我仍然有一些困难。 I'm using the following command /usr/bin/php home/domain.com/public_html/cron/script.php I receive the following error Status: 404 Not Found X-Powered-By: PHP/5.2.8 Content-type: text/html我正在使用以下命令 /usr/bin/php home/domain.com/public_html/cron/script.php 我收到以下错误状态:404 Not Found X-Powered-By:PHP/5.2.8 Content-type :文本/html

No input file specified.未指定输入文件。

i'm using Cpanel, the file is hosted on domain.com/cron/script.php Anyideas, thanks :p我正在使用 Cpanel,该文件托管在 domain.com/cron/script.php Anyideas,谢谢:p

Put a leading slash on the script name, ie在脚本名称上放置一个前导斜杠,即

/usr/bin/php /home/domain.com/public_html/cron/script.php

Unless you actually intend to run the script through the web, as in lacqui's answer, and you don't mind random third parties being able to run it any time they like, there's no reason you should put it inside your public_html directory;除非您真的打算通过网络运行脚本,如 lacqui 的回答,并且您不介意随机第三方能够在他们喜欢的任何时间运行它,否则您没有理由将它放在您的 public_html 目录中; quite the opposite.恰恰相反。

Try:尝试:

wget -O - http://domain.com/cron/script.php

and see if you get a better result.看看你是否得到更好的结果。

Edit: added "- O - " to not write output to home folder.编辑:添加了“- O - ”以不将输出写入主文件夹。

I'm realising that it is an old question and that you may have found a solution but none of the answers above helped me and I was getting the same 404 error when I was running a cron script.我意识到这是一个老问题,您可能已经找到了解决方案,但上述答案都没有帮助我,并且在运行 cron 脚本时遇到了相同的 404 错误。

The problem was related to the way in which the path to the php script was written.问题与编写 php 脚本路径的方式有关。 The path must start from public_html like this /usr/bin/php public_html/public/index.php路径必须像这样从 public_html 开始/usr/bin/php public_html/public/index.php

您可能需要使用称为 php-cli 的二进制文件,而不仅仅是 php。

In several shared hosting wget and curl commands are not available from cron.在几个共享主机中,cron 不提供wgetcurl命令。 If one wants to execute a web (http) request from cron, then it can be done by calling the desired web url as php curl inside cron php script.如果想要从 cron 执行web (http)请求,那么可以通过在 cron php 脚本中将所需的 web url 调用为 php curl 来完成。

Below is an example code to be put inside cron php file:下面是要放在 cron php 文件中的示例代码:

<?php
function callRemoteHttp($url)
{

    $curl = curl_init();    

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);
    $ret_arr = array('data' => $result, 'status_code' => curl_getinfo($curl, CURLINFO_HTTP_CODE));
    curl_close($curl);

    return $ret_arr;
}
$ret = callRemoteHttp('http://example.com?param1=value1&param2=value2');
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM