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

  1. 代码:
    /*
    @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;
    }
    }
  2. 测试:
    $ret = sock_send(
    'json',
    '192.168.8.81',
    array(
        'name'=>'lee'
    )
    );
    if($ret){
    echo '发送成功';
    }
  3. 输出:
    发送成功

猜你喜欢

转载自blog.51cto.com/12173069/2123461