php使用fsockopen请求方法,支持https/header设置/代理请求等定制
  2E99YFcvW02z 2023年11月02日 24 0


代理请求示例:

$re = request("http://127.0.0.1:8087", 'GET https://docs.google.com/viewer?url=http%3A%2F%2Ficon.chinahrd.net%2Fuploadfile%2FdocView%2FtoolDirLink%2Fhrm_jc%2Fjxts_1.ppt&embedded=true&mobile=true  HTTP/1.0', 'proxy', array('Host' => '127.0.0.1'));var_dump($re);exit;

------------------代理请求返回数据部分---
GET https://docs.google.com/viewer?url=http%3A%2F%2Ficon.chinahrd.net%2Fuploadfile%2FdocView%2FtoolDirLink%2Fhrm_jc%2Fjxts_1.ppt&embedded=true&mobile=true  HTTP/1.0Host: 127.0.0.1array(2) {["body"]=>string(18297) "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><scripttype="text/javascript">(function(){var a=function(e){this.t={};this.tick=function(e,i,d){d=void 0!=d?d:(new Date).getTime();this.t[e]=[d,i]};this.tick("start",null,e)},b=new a;window.jstiming={Timer:a,load:b};if(window.performance&&window.performance.timing){var c=window.performance.timing,f=window.jstiming.load,g=c.navigationStart,h=c.responseStart;0<g&&h>=g&&(f.tick("_wtsrt",void 0,g),f.tick("wtsrt_","_wtsrt",h),f.tick("tbsd_","wtsrt_"))}try{var j=null;window.chrome&&window.chrome.csi&&(j=Math.floor(window.chrome.csi().pageT),f&&0<g&&(f.tick("_tbnd",void 0,window.chrome.csi().startE),f.tick("tbnd_","_tbnd",g)));null==j&&window.gtbExternal&&(j=window.gtbExternal.pageT());null==j&&window.external&&(j=window.external.pageT,f&&0<g&&(f.tick("_tbnd",void 0,window.external.startE),f.tick("tbnd_","_tbnd",g)));j&&(window.jstiming.pt=j)}catch(k){};})();</script><metaname="viewport" content="initial-scale=1.0; maximum-scale=1.0;                     user-scalable=no;"><title>Powered by Google Docs</title><styletype="text/css">

---------------------------代码----------------
/*
 * 使用http接口请求数据
 * 可以在$url按格式指定协议与端口 https://domain.com:443/path?querystring
 * 返回array
 * $method = 'PROXY'时,$post=" GET url  HTTP/1.0\r\n",也就是代理请求的方法自己设置
 */
function request($url = '', $post = null /* 数组*/, $method = 'GET', $header = null, $timeout = 20 /* ms */) {
    if (empty($url)) return array('error' => 'url必须指定');
    $url = parse_url($url);
    $method = strtoupper(trim($method));
    $method = empty($method) ? 'GET' : $method;
    $scheme = strtolower($url['scheme']);
    $host = $url['host'];
    $path = $url['path'];
    empty($path) and ($path = '/');
    $query = $url['query'];
    $port = isset($url['port']) ? (int)$url['port'] : ('https' == $scheme ? 443 : 80);
    $protocol = 'https' == $scheme ? 'ssl://' : '';
    
    if (!$res = fsockopen($protocol.$host, (int)$port, $errno, $errstr, (int)$timeout)) {
        return array('error' => mb_convert_encoding($errstr, 'UTF-8', 'UTF-8,GB2312'), 'errorno' => $errno);
    } else {
        $crlf = "\r\n";
        $commonHeader = $method == 'PROXY' ? array() : array(
            'Host' => $host
            ,'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0'
            ,'Content-Type' => 'POST' == $method ? 'application/x-www-form-urlencoded' : 'text/html; charsert=UTF-8'
            ,'Connection' => 'Close'
        );                
        is_array($header) and ($commonHeader = array_merge($commonHeader, $header));
        
        foreach ($commonHeader as $key => & $val) {
            $val = str_replace(array("\n", "\r", ':'), '', $val);
            $key = str_replace(array("\n", "\r", ':'), '', $key);
            $val = "{$key}: {$val}{$crlf}";
        }     
        
        if ($method == 'PROXY') {
            $post = trim(str_replace(array("\n", "\r"), '', $post)).$crlf;
            
            if (empty($post)) return array('error' => '使用代理时,必须指定代理请求方法($post参数)');
        } else if (!is_array($post)) {
            $post = array();
        }
        
        switch ($method) {
            case 'POST':                        
                $post = http_build_query($post);
                $query = empty($query) ? '' : '?'.$query;
                $commonHeader[] = 'Content-Length: '.strlen($post).$crlf;
                $post = empty($post) ? '' : $crlf.$post.$crlf;
                $commonHeader = implode('', $commonHeader);
                $request = "{$method} {$path}{$query} HTTP/1.1{$crlf}"
                            ."{$commonHeader}"
                            .$post
                            .$crlf;//表示提交结束了
                break;
            case 'PROXY'://代理
                $commonHeader = implode('', $commonHeader);
                $request =  $post
                            .$commonHeader
                            .$crlf;//表示提交结束了                
                break;
            case 'GET':
            default:
                empty($query) ? ($query = array()) : parse_str($query, $query);
                $query = array_merge($query, $post);
                $query = http_build_query($query);
                $commonHeader = implode('', $commonHeader);
                $query = empty($query) ? '' : '?'.$query;
                $request =  "{$method} {$path}{$query} HTTP/1.1{$crlf}"
                            ."{$commonHeader}"
                            .$crlf;//表示提交结束了
        }

        fwrite($res, $request);
        $reponse = '';
        
        while (!feof($res)) {
            $reponse .= fgets($res, 128);
        }
        
        fclose($res);
        $pos = strpos($reponse, $crlf . $crlf);//查找第一个分隔                
        if($pos === false) return array('reponse' => $reponse);
        $header = substr($reponse, 0, $pos);
        $body = substr($reponse, $pos + 2 * strlen($crlf));                
        return array('body' => $body, 'header' => $header);
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  PVcilKyJJTzb   2023年11月02日   50   0   0 nginxdockerhtml
  YVSd8ahJJ3uw   2023年11月02日   92   0   0 CISSPchrome网络安全
2E99YFcvW02z