很多情況下 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 不顯示下載速度等資訊。