码迷,mamicode.com
首页 > Web开发 > 详细

php异步请求数据(转发请求到别处处理)

时间:2018-06-02 16:40:29      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:php异步请求数据(转发请求到别处处理)

  • 代码:
    /*
    @desc:模拟get、post、json异步请求数据
    @param method 请求类型 get|post|json
    @param url 请求的url地址,如:群发邮件
    @param data 请求数据
    */
    function sock_send($method,$url,$data=array()){
    $url = ‘http://‘.$url;
    if(strtolower($method) == ‘get‘){
        $query = http_build_query($data);
        $info = parse_url($url);
        $fp = fsockopen($info["host"], 80, $errno, $errstr, 8);
        $head = "GET ".$info[‘path‘]."?".$info["query"].trim($query)." HTTP/1.0\r\n";
        $head .= "Host: ".$info[‘host‘]."\r\n";
        $head .= "Connection:close\r\n\r\n";
        $write = fputs($fp, $head);
        return $write;
    }elseif(strtolower($method) == ‘post‘){
        $query = http_build_query($data);
        $info = parse_url($url);
        $fp = fsockopen($info["host"], 80, $errno, $errstr, 8);
        $head = "POST ".$info[‘path‘]."?".$info["query"]." HTTP/1.0\r\n";
        $head .= "Host: ".$info[‘host‘]."\r\n";
        $head .= "Referer: http://".$info[‘host‘].$info[‘path‘]."\r\n";
        $head .= "Content-type: application/x-www-form-urlencoded\r\n";
        $head .= "Content-Length: ".strlen(trim($query))."\r\n";
        $head .= "Connection:close\r\n\r\n";
        $head .= trim($query);
        $write = fputs($fp, $head);
        return $write;
    }elseif(strtolower($method) == ‘json‘){
        $query = json_encode($data);
        $info = parse_url($url);
        $fp = fsockopen($info["host"], 80, $errno, $errstr, 8);
        $head = "POST ".$info[‘path‘]."?".$info["query"]." HTTP/1.0\r\n";
        $head .= "Host: ".$info[‘host‘]."\r\n";
        $head .= "Referer: http://".$info[‘host‘].$info[‘path‘]."\r\n";
        $head .= "Content-type: application/json\r\n";
        $head .= "Content-Length: ".strlen(trim($query))."\r\n";
        $head .= "Connection:close\r\n\r\n";
        $head .= trim($query);
        $write = fputs($fp, $head);
        return $write;
    }else{
        return false;
    }
    }
  • 测试:
    $ret = sock_send(
    ‘json‘,
    ‘192.168.8.81‘,
    array(
        ‘name‘=>‘lee‘
    )
    );
    if($ret){
    echo ‘发送成功‘;
    }
  • 输出:
    发送成功
  • php异步请求数据(转发请求到别处处理)

    标签:php异步请求数据(转发请求到别处处理)

    原文地址:http://blog.51cto.com/12173069/2123461

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!