php利用fscokopen()函数执行异步调用

<?php
/**
 * php利用fscokopen()函数执行异步调用
* 参考鸟哥的:使用fscok实现异步调用PHPhttp://www.laruence.com/2008/04/16/98.html */ class asyncRequest {    /**     * post 方式传参
 * @param string $url 请求url     * @param array $data 参数
 * @return bool     */    public function postSend($url, $data=[])    {        $method = "POST";    //通过POST传递一些参数给要触发的脚本
   $url_array = parse_url($url);   //获取url信息,以便拼凑http header        $port = isset($url_array['port']) ? $url_array['port'] : 80;        $query = isset($data) ? http_build_query($data) : '';        $errno = 0;        $errstr = '';        $fp = fsockopen($url_array['host'], $port, $errno, $errstr, 30);        if(!$fp) {            file_put_contents('1.txt',"errno={$errno}---errstr={$errstr}");            return false;        }        //构建header        $getPath = $url_array['path'];        $header = $method.' '.$getPath." HTTP/1.1\r\n";        $header .= 'Host:'.$url_array['host']."\r\n";        $header .= 'Content-length:'.strlen($query)."\r\n";     //POST长度
   $header .= "Content-type:application/x-www-form-urlencoded\r\n";    //POST数据
   $header .= "Connection:Close\r\n\r\n";        $header .= $query;        fwrite($fp, $header);        //var_dump(fread($fp, 1024)); //不关心服务器返回
   fclose($fp);        return true;    }    /**     * GET 方式传参
 * @param string $url 请求url     * @param array $data 参数
 * @return bool     */    public function getSend($url, $data=[])    {        $method = "GET";    //通过POST传递一些参数给要触发的脚本
   $url_array = parse_url($url);   //获取url信息,以便拼凑http header        $port = isset($url_array['port']) ? $url_array['port'] : 80;        $query = isset($data) ? http_build_query($data) : '';        $errno = 0;        $errstr = '';        $fp = fsockopen($url_array['host'], $port, $errno, $errstr, 30);        if(!$fp) {            file_put_contents('1.txt',"errno={$errno}---errstr={$errstr}");            return false;        }        //构建header        $getPath = $url_array['path'].'?'.$query;        $header = $method.' '.$getPath." HTTP/1.1\r\n";        $header .= 'Host:'.$url_array['host']."\r\n";        $header .= "Connection:Close\r\n\r\n";        fwrite($fp, $header);        //var_dump(fread($fp, 1024)); //不关心服务器返回
   fclose($fp);        return true;    } } //test $client = new asyncRequest(); //$client->postSend('http://www.demo.com/usefulCode/asyncCall/b.php',['param'=> 'hello world, post']); $client->getSend('http://www.demo.com/usefulCode/asyncCall/b.php',['param'=> 'hello world, get']);

b.php:

<?php
ignore_user_abort(TRUE); //如果客户端断开连接,不会引起脚本abort.
set_time_limit(0);//取消脚本执行延时上限
sleep(10); $param = isset($_POST['param']) ? $_POST['param'] : $_GET['param'];//$_REQUEST['param'] if(file_exists('1.txt')){    @unlink('1.txt'); } file_put_contents('1.txt',$param);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值