很多情况下 PHP 需要定时自动执行,这个可以用 Crontab 排程定时执行实现,以下是几种实现方法:
方法一:
1. 在 PHP 程式的第一行加入:
|
1 2 3 4 |
#!/usr/bin/php -q <?php $foo = 123; ?> |
请留意,我的 PHP 是路径在 /usr/bin/php,请根据你的 PHP 执行档位置作出修改。
2. 将 PHP 程式给予可执行权限:
chmod +x testing.php
3. 执行 crontab -e,然后加入以下内容:
00 00 * * * /path/to/testing.php > /dev/null 2>&2
以上语法会在每天的零时零分执行 /path/to/testing.php
方法二:
另一个方法是不用在 PHP 程式的第一行加入 “#!/usr/bin/php -q”,可以省略第一步及第二步,直接执行 crontab -e,并输入以下内容:
00 00 * * * /usr/bin/php -q /path/to/testing.php > /dev/null 2>&2
这个方法的结果跟方法一的结果相同。
方法三:
上面的方法是透过 CLI 执行 PHP,执行身份会时设定 crontab 的帐号身份,如果需要透过像一般网页的方法加载 PHP,可以用 curl 或 lynx 等工具,以下会以 curl 为例子。
如果没有安装 curl, 首先需要先安装 curl:
RHEL / CentOS:
Debian / Ubuntu / Mint:
安装好 curl 后,执行 crontab -e,并输入以下内容:
00 00 * * * /usr/bin/curl -l http://www.yourdomain.com/testing.php > /dev/null 2>&2
以上一行会在每晚 12:00 用 curl 开启 http://www.yourdomain.com/testing.php 页面,其中加上 -l 是为了该 curl 不显示下载速度等资讯。