发件人文件示例 ./ajax/sender.php
脚本发送POST ->它向主机发出完整的请求,但它不会等待来自服务器的应答:CURLOPT_HEADER(0)我们不需要来自服务器的标头)和CURLOPT_RETURNTRANSFER(false)我们不需要来自服务器的数据。CURLOPT_TIMEOUT - 额外的procteted:我们在响应服务器上只发送了1ms之后等待,如果服务器保留我们,这是额外的质量,不再等待任何ms。### 注意 ###HTTP1.1 有一个最大 16kb 的软件包。HTTP2有36kb一个pacakge。如果 POST 更大,则服务器将连续发送许多包 = $SIZE%16kb
$url = 'https://127.0.0.1/ajax/received.php';
$curl = curl_init();
$post['test'] = 'examples daata'; // our data todo in received
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_TIMEOUT, 1); //if your connect is longer than 1s it lose data in POST better is finish script in recevie
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');
编辑 2019 如果你使用 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');
旧版本: