发送者文件示例 ./ajax/sender.php
脚本发送POST请求 -> 它向主机发出完整的请求,但不等待服务器的响应:CURLOPT_HEADER(0)我们不需要来自服务器的头信息)和CURLOPT_RETURNTRANSFER(false)我们不需要来自服务器的数据。CURLOPT_TIMEOUT - 额外保护:我们只在发送后等待1毫秒以响应服务器,这是额外的保证,如果服务器保持我们,则不再等待任何毫秒。### 注意 ### HTTP1.1每个包最大16kb。HTTP2每个包36kb。如果POST更大,服务器将以多个连续的包发送= $SIZE%16kb
$url = 'https://127.0.0.1/ajax/received.php';
$curl = curl_init();
$post['test'] = 'examples daata';
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_POST, TRUE);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_USERAGENT, 'api');
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_FORBID_REUSE, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($curl, CURLOPT_DNS_CACHE_TIMEOUT, 100);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
curl_exec($curl);
curl_close($curl);
收到文件示例 ./ajax/received.php
ignore_user_abort(true); //if connect is close, we continue php script in background up to script will be end
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
header("Content-Length: 1");
### we just close connect above if webbrowser, or request waiting on answer ( we know we set CURLOP to not wait) ###
ob_end_clean(); //just flush all content if exists to request. If server still waiting on answer.
//HERE all script doing in background: Example
$this->db->query('UPDATE new_hook_memory SET new=new+1 WHERE id=1');
如果你使用fastcgi,当fastcgi完成并且浏览器关闭连接时,脚本仍然会一直运行到结束。
如何结束脚本: 使用PHP mod_fcgi和fastcgi_finish_request();
对于Apache2:
ob_end_flush();
flush();
对于php-fpm
fastcgi_finish_request(); $this->db->query('UPDATE new_hook_memory SET new=new+1 WHERE id=1');
旧版本:
pfsockopen
打开持久套接字连接,或者分叉 curl 进程,或者如果您不关心实际请求的延迟(例如在日志场景中),您可以将请求记录到日志文件中,并使用后台进程(如 cron)发送带外请求使用日志条目。 - konrad