php用fsockopen实现post提交数据并获得返回数据

/**
* 函数介绍: 用于post方式提交数据
* 输入参数: 完整url, 数据
* 返回值 : 接口返回值
*/
function post_it($url, $data = '', $timeout = '6') {
$urls = parse_url($url);
if (!$urls) {
return "-500";
}
$port = isset($urls['port']) ? $urls['port'] : null; //isset()判断
if (!$port) {
$port = "80";
}
$host = $urls['host'];
//----------------------------------------------//
$httpheader = "POST " . $url . " HTTP/1.0" . "\r\n" . "Accept:*/*" . "\r\n" . "Accept-Language:zh-cn" . "\r\n" . "Referer:" . $url . "\r\n" . "Content-Type:application/x-www-form-urlencoded" . "\r\n" . "User-Agent:Mozilla/4.0(compatible;MSIE 7.0;Windows NT 5.1)" . "\r\n" . "Host:" . $host . "\r\n" . "Content-Length:" . strlen($data) . "\r\n" . "\r\n" . $data;
$fd = fsockopen($host, $port);
if (!is_resource($fd)) {
return "fsockopen failed";
}
fwrite($fd, $httpheader);
stream_set_blocking($fd, TRUE);
stream_set_timeout($fd, $timeout);
$info = stream_get_meta_data($fd);
$gets = "";
while ((!feof($fd)) && (!$info['timed_out'])) {
$data .= fgets($fd, 8192);
$info = stream_get_meta_data($fd);
@ob_flush();
flush();
}
if ($info['timed_out']) {
return "timeout";
} else {
//echo $data;
$contentInfo = explode("\n\n", str_replace("\r", "", $data)); if (!strstr($contentInfo[0], "HTTP/1.1 200 OK")) {
return -10;
}
return trim($contentInfo[1]);
}
}

/**
 * 函数介绍:    用于post方式提交数据
 * 输入参数:    完整url, 数据
 * 返回值  :    接口返回值
 */
function post_it($url, $data = '', $timeout = '6') {
    $urls = parse_url($url);
    if (!$urls) {
        return "-500";
    }
    $port = isset($urls['port']) ? $urls['port'] : null; //isset()判断
    if (!$port) {
        $port = "80";
    }
    $host = $urls['host'];
    //----------------------------------------------//
    $httpheader = "POST " . $url . " HTTP/1.0" . "\r\n" . "Accept:*/*" . "\r\n" . "Accept-Language:zh-cn" . "\r\n" . "Referer:" . $url . "\r\n" . "Content-Type:application/x-www-form-urlencoded" . "\r\n" . "User-Agent:Mozilla/4.0(compatible;MSIE 7.0;Windows NT 5.1)" . "\r\n" . "Host:" . $host . "\r\n" . "Content-Length:" . strlen($data) . "\r\n" . "\r\n" . $data;
    $fd = fsockopen($host, $port);
    if (!is_resource($fd)) {
        return "fsockopen failed";
    }
    fwrite($fd, $httpheader);
    stream_set_blocking($fd, TRUE);
    stream_set_timeout($fd, $timeout);
    $info = stream_get_meta_data($fd);
    $gets = "";
    while ((!feof($fd)) && (!$info['timed_out'])) {
        $data .= fgets($fd, 8192);
        $info = stream_get_meta_data($fd);
        @ob_flush();
        flush();
    }
    if ($info['timed_out']) {
        return "timeout";
    } else {
        //echo $data;
        $contentInfo = explode("\n\n", str_replace("\r", "", $data));
        
        if (!strstr($contentInfo[0], "HTTP/1.1 200 OK")) {
            return -10;
        }
        return trim($contentInfo[1]);
    }
}

上一篇:PHP模拟发送POST请求之三、用Telnet和fsockopen()模拟发送POST信息


下一篇:linux下命令运行目录上程序前面要加./