正常情况下,PHP执行的都是同步请求,代码自上而下依次执行,但有些场景如发送邮件、执行耗时任务等操作时就不适用于同步请求,只能使用异步处理请求。
<?php
function connect($host, $url)
{
// check whether the curl function is exist or not.
if (function_exists('curl_version')) {
connectCurl($host, $url);
return;
}
// default
connectFwrite($host, $url);
return;
}
function connectCurl($host, $url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://" . $host . '/' . $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$response = curl_exec($ch);
curl_close($ch);
}
function connectFwrite($host, $url)
{
$fp = @fsockopen($host, 80, $errorNum, $errorStr);
if (!$fp) {
echo 'There was an error connecting to the site.';
exit;
}
$request = "GET /" . $url . " HTTP/1.1\r\n";
$request .= "Host: " . $host . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($fp, $request);
fclose($fp);
}
$host="";
$url ="";
connect($host, $url);
echo "Cronjob processed.\r\n";
return;
最后在用crontab设置定时访问一下这个文件就可以达到效果!