php 使用fsockopen函数发送URL请求

7月前发布 147 0 0

admin

保密 | 这个家伙很懒,什么都没有留下
/**
 * 使用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;
}
fsockopen限制更少一点,前提是你的环境支持此函数,默认发送邮件就是用的这个
赞赏支持

登录 后发表评论
0条评论
    还没有人评论过~