1. 程式人生 > >php異步請求數據(轉發請求到別處處理)

php異步請求數據(轉發請求到別處處理)

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異步請求數據(轉發請求到別處處理)