php 使用fsockopen函数发送URL请求

/**
 * 使用fsockopen发送URL请求
 * @param $url
 * @param $method: GET、POST等
 * @param array $params
 * @param array $header
 * @param int $timeout
 * @return array|bool
 */
function sendHttpRequest($url, $method = 'GET', $params = [], $header = [], $timeout = 30)
{
    $urlInfo = parse_url($url);

    if (isset($urlInfo['scheme']) && strcasecmp($urlInfo['scheme'], 'https') === 0) //HTTPS
    {
        $prefix = 'ssl://';
        $port = 443;
    }else{  //HTTP
        $prefix = 'tcp://';
        $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80;
    }

    $host = $urlInfo['host'];
    $path = isset($urlInfo['path']) ? $urlInfo['path'] : '/';

    if(!empty($params) && is_array($params))
    {
        $params = http_build_query($params);
    }

    $contentType = '';
    $contentLength = '';
    $requestBody = '';
    if($method === 'GET')
    {
        $params = $params ? '?' . $params : '';
        $path .= $params;
    }else{
        $requestBody = $params;
        $contentType = "Content-Type: application/x-www-form-urlencoded\r\n";
        $contentLength = "Content-Length: " . strlen($requestBody) . "\r\n";
    }


    $auth = '';
    if(!empty($urlInfo['user']))
    {
        $auth = 'Authorization: Basic ' . base64_encode($urlInfo['user'] . ':' . $urlInfo['pass']) . "\r\n";
    }

    if($header && is_array($header))
    {
        $tmpString = '';
        foreach ($header as $key => $value)
        {
            $tmpString .= $key . ': ' . $value . "\r\n";
        }
        $header = $tmpString;
    }else{
        $header = '';
    }

    $out = "$method $path HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= $auth;
    $out .= $header;
    $out .= $contentType;
    $out .= $contentLength;
    $out .= "Connection: Close\r\n\r\n";
    $out .= $requestBody;//post发送数据前必须要有两个换行符\r\n

    $fp = fsockopen($prefix . $host, $port, $errno, $errstr, $timeout);
    if(!$fp)
    {
        return false;
    }

    if(!fwrite($fp, $out))
    {
        return false;
    }

    $response = '';
    while(!feof($fp))
    {
        $response .= fread($fp, 1024);
    }

    if(!$response)
    {
        return false;
    }

    fclose($fp);

    $separator = '/\r\n\r\n|\n\n|\r\r/';

    list($responseHeader, $responseBody) = preg_split($separator, $response, 2);

    $httpResponse = array(
        'header' => $responseHeader,
        'body' => $responseBody
    );

    return $httpResponse;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值