[PHP] ThinkPHP Http工具类(用于远程采集 远程下载) →→→→→进入此内容的聊天室

来自 , 2019-04-21, 写在 PHP, 查看 127 次.
URL http://www.code666.cn/view/b5b03f06
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11.  
  12. /**
  13.  * Http 工具类
  14.  * 提供一系列的Http方法
  15.  * @category   ORG
  16.  * @package  ORG
  17.  * @subpackage  Net
  18.  * @author    liu21st <liu21st@gmail.com>
  19.  */
  20. class Http {
  21.  
  22.     /**
  23.      * 采集远程文件
  24.      * @access public
  25.      * @param string $remote 远程文件名
  26.      * @param string $local 本地保存文件名
  27.      * @return mixed
  28.      */
  29.     static public function curlDownload($remote,$local) {
  30.         $cp = curl_init($remote);
  31.         $fp = fopen($local,"w");
  32.         curl_setopt($cp, CURLOPT_FILE, $fp);
  33.         curl_setopt($cp, CURLOPT_HEADER, 0);
  34.         curl_exec($cp);
  35.         curl_close($cp);
  36.         fclose($fp);
  37.     }
  38.  
  39.    /**
  40.     * 使用 fsockopen 通过 HTTP 协议直接访问(采集)远程文件
  41.     * 如果主机或服务器没有开启 CURL 扩展可考虑使用
  42.     * fsockopen 比 CURL 稍慢,但性能稳定
  43.     * @static
  44.     * @access public
  45.     * @param string $url 远程URL
  46.     * @param array $conf 其他配置信息
  47.     *        int   limit 分段读取字符个数
  48.     *        string post  post的内容,字符串或数组,key=value&形式
  49.     *        string cookie 携带cookie访问,该参数是cookie内容
  50.     *        string ip    如果该参数传入,$url将不被使用,ip访问优先
  51.     *        int    timeout 采集超时时间
  52.     *        bool   block 是否阻塞访问,默认为true
  53.     * @return mixed
  54.     */
  55.     static public function fsockopenDownload($url, $conf = array()) {
  56.         $return = '';
  57.         if(!is_array($conf)) return $return;
  58.  
  59.         $matches = parse_url($url);
  60.         !isset($matches['host'])        && $matches['host']     = '';
  61.         !isset($matches['path'])        && $matches['path']     = '';
  62.         !isset($matches['query'])       && $matches['query']    = '';
  63.         !isset($matches['port'])        && $matches['port']     = '';
  64.         $host = $matches['host'];
  65.         $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
  66.         $port = !empty($matches['port']) ? $matches['port'] : 80;
  67.  
  68.         $conf_arr = array(
  69.             'limit'             =>      0,
  70.             'post'              =>      '',
  71.             'cookie'    =>      '',
  72.             'ip'                =>      '',
  73.             'timeout'   =>      15,
  74.             'block'             =>      TRUE,
  75.             );
  76.  
  77.         foreach (array_merge($conf_arr, $conf) as $k=>$v) ${$k} = $v;
  78.  
  79.         if($post) {
  80.             if(is_array($post))
  81.             {
  82.                 $post = http_build_query($post);
  83.             }
  84.             $out  = "POST $path HTTP/1.0\r\n";
  85.             $out .= "Accept: */*\r\n";
  86.             //$out .= "Referer: $boardurl\r\n";
  87.             $out .= "Accept-Language: zh-cn\r\n";
  88.             $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
  89.             $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
  90.             $out .= "Host: $host\r\n";
  91.             $out .= 'Content-Length: '.strlen($post)."\r\n";
  92.             $out .= "Connection: Close\r\n";
  93.             $out .= "Cache-Control: no-cache\r\n";
  94.             $out .= "Cookie: $cookie\r\n\r\n";
  95.             $out .= $post;
  96.         } else {
  97.             $out  = "GET $path HTTP/1.0\r\n";
  98.             $out .= "Accept: */*\r\n";
  99.             //$out .= "Referer: $boardurl\r\n";
  100.             $out .= "Accept-Language: zh-cn\r\n";
  101.             $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
  102.             $out .= "Host: $host\r\n";
  103.             $out .= "Connection: Close\r\n";
  104.             $out .= "Cookie: $cookie\r\n\r\n";
  105.         }
  106.         $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
  107.         if(!$fp) {
  108.             return '';
  109.         } else {
  110.             stream_set_blocking($fp, $block);
  111.             stream_set_timeout($fp, $timeout);
  112.             @fwrite($fp, $out);
  113.             $status = stream_get_meta_data($fp);
  114.             if(!$status['timed_out']) {
  115.                 while (!feof($fp)) {
  116.                     if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
  117.                         break;
  118.                     }
  119.                 }
  120.  
  121.                 $stop = false;
  122.                 while(!feof($fp) && !$stop) {
  123.                     $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
  124.                     $return .= $data;
  125.                     if($limit) {
  126.                         $limit -= strlen($data);
  127.                         $stop = $limit <= 0;
  128.                     }
  129.                 }
  130.             }
  131.             @fclose($fp);
  132.             return $return;
  133.         }
  134.     }
  135.  
  136.     /**
  137.      * 下载文件
  138.      * 可以指定下载显示的文件名,并自动发送相应的Header信息
  139.      * 如果指定了content参数,则下载该参数的内容
  140.      * @static
  141.      * @access public
  142.      * @param string $filename 下载文件名
  143.      * @param string $showname 下载显示的文件名
  144.      * @param string $content  下载的内容
  145.      * @param integer $expire  下载内容浏览器缓存时间
  146.      * @return void
  147.      */
  148.     static public function download ($filename, $showname='',$content='',$expire=180) {
  149.         if(is_file($filename)) {
  150.             $length = filesize($filename);
  151.         }elseif(is_file(UPLOAD_PATH.$filename)) {
  152.             $filename = UPLOAD_PATH.$filename;
  153.             $length = filesize($filename);
  154.         }elseif($content != '') {
  155.             $length = strlen($content);
  156.         }else {
  157.             throw_exception($filename.L('下载文件不存在!'));
  158.         }
  159.         if(empty($showname)) {
  160.             $showname = $filename;
  161.         }
  162.         $showname = basename($showname);
  163.                 if(!empty($filename)) {
  164.                 $type = mime_content_type($filename);
  165.                 }else{
  166.                         $type    =       "application/octet-stream";
  167.                 }
  168.         //发送Http Header信息 开始下载
  169.         header("Pragma: public");
  170.         header("Cache-control: max-age=".$expire);
  171.         //header('Cache-Control: no-store, no-cache, must-revalidate');
  172.         header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
  173.         header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
  174.         header("Content-Disposition: attachment; filename=".$showname);
  175.         header("Content-Length: ".$length);
  176.         header("Content-type: ".$type);
  177.         header('Content-Encoding: none');
  178.         header("Content-Transfer-Encoding: binary" );
  179.         if($content == '' ) {
  180.             readfile($filename);
  181.         }else {
  182.                 echo($content);
  183.         }
  184.         exit();
  185.     }
  186.  
  187.     /**
  188.      * 显示HTTP Header 信息
  189.      * @return string
  190.      */
  191.     static function getHeaderInfo($header='',$echo=true) {
  192.         ob_start();
  193.         $headers        = getallheaders();
  194.         if(!empty($header)) {
  195.             $info       = $headers[$header];
  196.             echo($header.':'.$info."\n"); ;
  197.         }else {
  198.             foreach($headers as $key=>$val) {
  199.                 echo("$key:$val\n");
  200.             }
  201.         }
  202.         $output         = ob_get_clean();
  203.         if ($echo) {
  204.             echo (nl2br($output));
  205.         }else {
  206.             return $output;
  207.         }
  208.  
  209.     }
  210.  
  211.     /**
  212.      * HTTP Protocol defined status codes
  213.      * @param int $num
  214.      */
  215.         static function sendHttpStatus($code) {
  216.                 static $_status = array(
  217.                         // Informational 1xx
  218.                         100 => 'Continue',
  219.                         101 => 'Switching Protocols',
  220.  
  221.                         // Success 2xx
  222.                         200 => 'OK',
  223.                         201 => 'Created',
  224.                         202 => 'Accepted',
  225.                         203 => 'Non-Authoritative Information',
  226.                         204 => 'No Content',
  227.                         205 => 'Reset Content',
  228.                         206 => 'Partial Content',
  229.  
  230.                         // Redirection 3xx
  231.                         300 => 'Multiple Choices',
  232.                         301 => 'Moved Permanently',
  233.                         302 => 'Found',  // 1.1
  234.                         303 => 'See Other',
  235.                         304 => 'Not Modified',
  236.                         305 => 'Use Proxy',
  237.                         // 306 is deprecated but reserved
  238.                         307 => 'Temporary Redirect',
  239.  
  240.                         // Client Error 4xx
  241.                         400 => 'Bad Request',
  242.                         401 => 'Unauthorized',
  243.                         402 => 'Payment Required',
  244.                         403 => 'Forbidden',
  245.                         404 => 'Not Found',
  246.                         405 => 'Method Not Allowed',
  247.                         406 => 'Not Acceptable',
  248.                         407 => 'Proxy Authentication Required',
  249.                         408 => 'Request Timeout',
  250.                         409 => 'Conflict',
  251.                         410 => 'Gone',
  252.                         411 => 'Length Required',
  253.                         412 => 'Precondition Failed',
  254.                         413 => 'Request Entity Too Large',
  255.                         414 => 'Request-URI Too Long',
  256.                         415 => 'Unsupported Media Type',
  257.                         416 => 'Requested Range Not Satisfiable',
  258.                         417 => 'Expectation Failed',
  259.  
  260.                         // Server Error 5xx
  261.                         500 => 'Internal Server Error',
  262.                         501 => 'Not Implemented',
  263.                         502 => 'Bad Gateway',
  264.                         503 => 'Service Unavailable',
  265.                         504 => 'Gateway Timeout',
  266.                         505 => 'HTTP Version Not Supported',
  267.                         509 => 'Bandwidth Limit Exceeded'
  268.                 );
  269.                 if(isset($_status[$code])) {
  270.                         header('HTTP/1.1 '.$code.' '.$_status[$code]);
  271.                 }
  272.         }
  273. }//类定义结束
  274. if( !function_exists ('mime_content_type')) {
  275.     /**
  276.      * 获取文件的mime_content类型
  277.      * @return string
  278.      */
  279.     function mime_content_type($filename) {
  280.        static $contentType = array(
  281.                         'ai'            => 'application/postscript',
  282.                         'aif'           => 'audio/x-aiff',
  283.                         'aifc'          => 'audio/x-aiff',
  284.                         'aiff'          => 'audio/x-aiff',
  285.                         'asc'           => 'application/pgp', //changed by skwashd - was text/plain
  286.                         'asf'           => 'video/x-ms-asf',
  287.                         'asx'           => 'video/x-ms-asf',
  288.                         'au'            => 'audio/basic',
  289.                         'avi'           => 'video/x-msvideo',
  290.                         'bcpio'         => 'application/x-bcpio',
  291.                         'bin'           => 'application/octet-stream',
  292.                         'bmp'           => 'image/bmp',
  293.                         'c'                     => 'text/plain', // or 'text/x-csrc', //added by skwashd
  294.                         'cc'            => 'text/plain', // or 'text/x-c++src', //added by skwashd
  295.                         'cs'            => 'text/plain', //added by skwashd - for C# src
  296.                         'cpp'           => 'text/x-c++src', //added by skwashd
  297.                         'cxx'           => 'text/x-c++src', //added by skwashd
  298.                         'cdf'           => 'application/x-netcdf',
  299.                         'class'         => 'application/octet-stream',//secure but application/java-class is correct
  300.                         'com'           => 'application/octet-stream',//added by skwashd
  301.                         'cpio'          => 'application/x-cpio',
  302.                         'cpt'           => 'application/mac-compactpro',
  303.                         'csh'           => 'application/x-csh',
  304.                         'css'           => 'text/css',
  305.                         'csv'           => 'text/comma-separated-values',//added by skwashd
  306.                         'dcr'           => 'application/x-director',
  307.                         'diff'          => 'text/diff',
  308.                         'dir'           => 'application/x-director',
  309.                         'dll'           => 'application/octet-stream',
  310.                         'dms'           => 'application/octet-stream',
  311.                         'doc'           => 'application/msword',
  312.                         'dot'           => 'application/msword',//added by skwashd
  313.                         'dvi'           => 'application/x-dvi',
  314.                         'dxr'           => 'application/x-director',
  315.                         'eps'           => 'application/postscript',
  316.                         'etx'           => 'text/x-setext',
  317.                         'exe'           => 'application/octet-stream',
  318.                         'ez'            => 'application/andrew-inset',
  319.                         'gif'           => 'image/gif',
  320.                         'gtar'          => 'application/x-gtar',
  321.                         'gz'            => 'application/x-gzip',
  322.                         'h'                     => 'text/plain', // or 'text/x-chdr',//added by skwashd
  323.                         'h++'           => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
  324.                         'hh'            => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
  325.                         'hpp'           => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
  326.                         'hxx'           => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
  327.                         'hdf'           => 'application/x-hdf',
  328.                         'hqx'           => 'application/mac-binhex40',
  329.                         'htm'           => 'text/html',
  330.                         'html'          => 'text/html',
  331.                         'ice'           => 'x-conference/x-cooltalk',
  332.                         'ics'           => 'text/calendar',
  333.                         'ief'           => 'image/ief',
  334.                         'ifb'           => 'text/calendar',
  335.                         'iges'          => 'model/iges',
  336.                         'igs'           => 'model/iges',
  337.                         'jar'           => 'application/x-jar', //added by skwashd - alternative mime type
  338.                         'java'          => 'text/x-java-source', //added by skwashd
  339.                         'jpe'           => 'image/jpeg',
  340.                         'jpeg'          => 'image/jpeg',
  341.                         'jpg'           => 'image/jpeg',
  342.                         'js'            => 'application/x-javascript',
  343.                         'kar'           => 'audio/midi',
  344.                         'latex'         => 'application/x-latex',
  345.                         'lha'           => 'application/octet-stream',
  346.                         'log'           => 'text/plain',
  347.                         'lzh'           => 'application/octet-stream',
  348.                         'm3u'           => 'audio/x-mpegurl',
  349.                         'man'           => 'application/x-troff-man',
  350.                         'me'            => 'application/x-troff-me',
  351.                         'mesh'          => 'model/mesh',
  352.                         'mid'           => 'audio/midi',
  353.                         'midi'          => 'audio/midi',
  354.                         'mif'           => 'application/vnd.mif',
  355.                         'mov'           => 'video/quicktime',
  356.                         'movie'         => 'video/x-sgi-movie',
  357.                         'mp2'           => 'audio/mpeg',
  358.                         'mp3'           => 'audio/mpeg',
  359.                         'mpe'           => 'video/mpeg',
  360.                         'mpeg'          => 'video/mpeg',
  361.                         'mpg'           => 'video/mpeg',
  362.                         'mpga'          => 'audio/mpeg',
  363.                         'ms'            => 'application/x-troff-ms',
  364.                         'msh'           => 'model/mesh',
  365.                         'mxu'           => 'video/vnd.mpegurl',
  366.                         'nc'            => 'application/x-netcdf',
  367.                         'oda'           => 'application/oda',
  368.                         'patch'         => 'text/diff',
  369.                         'pbm'           => 'image/x-portable-bitmap',
  370.                         'pdb'           => 'chemical/x-pdb',
  371.                         'pdf'           => 'application/pdf',
  372.                         'pgm'           => 'image/x-portable-graymap',
  373.                         'pgn'           => 'application/x-chess-pgn',
  374.                         'pgp'           => 'application/pgp',//added by skwashd
  375.                         'php'           => 'application/x-httpd-php',
  376.                         'php3'          => 'application/x-httpd-php3',
  377.                         'pl'            => 'application/x-perl',
  378.                         'pm'            => 'application/x-perl',
  379.                         'png'           => 'image/png',
  380.                         'pnm'           => 'image/x-portable-anymap',
  381.                         'po'            => 'text/plain',
  382.                         'ppm'           => 'image/x-portable-pixmap',
  383.                         'ppt'           => 'application/vnd.ms-powerpoint',
  384.                         'ps'            => 'application/postscript',
  385.                         'qt'            => 'video/quicktime',
  386.                         'ra'            => 'audio/x-realaudio',
  387.                         'rar'           => 'application/octet-stream',
  388.                         'ram'           => 'audio/x-pn-realaudio',
  389.                         'ras'           => 'image/x-cmu-raster',
  390.                         'rgb'           => 'image/x-rgb',
  391.                         'rm'            => 'audio/x-pn-realaudio',
  392.                         'roff'          => 'application/x-troff',
  393.                         'rpm'           => 'audio/x-pn-realaudio-plugin',
  394.                         'rtf'           => 'text/rtf',
  395.                         'rtx'           => 'text/richtext',
  396.                         'sgm'           => 'text/sgml',
  397.                         'sgml'          => 'text/sgml',
  398.                         'sh'            => 'application/x-sh',
  399.                         'shar'          => 'application/x-shar',
  400.                         'shtml'         => 'text/html',
  401.                         'silo'          => 'model/mesh',
  402.                         'sit'           => 'application/x-stuffit',
  403.                         'skd'           => 'application/x-koan',
  404.                         'skm'           => 'application/x-koan',
  405.                         'skp'           => 'application/x-koan',
  406.                         'skt'           => 'application/x-koan',
  407.                         'smi'           => 'application/smil',
  408.                         'smil'          => 'application/smil',
  409.                         'snd'           => 'audio/basic',
  410.                         'so'            => 'application/octet-stream',
  411.                         'spl'           => 'application/x-futuresplash',
  412.                         'src'           => 'application/x-wais-source',
  413.                         'stc'           => 'application/vnd.sun.xml.calc.template',
  414.                         'std'           => 'application/vnd.sun.xml.draw.template',
  415.                         'sti'           => 'application/vnd.sun.xml.impress.template',
  416.                         'stw'           => 'application/vnd.sun.xml.writer.template',
  417.                         'sv4cpio'       => 'application/x-sv4cpio',
  418.                         'sv4crc'        => 'application/x-sv4crc',
  419.                         'swf'           => 'application/x-shockwave-flash',
  420.                         'sxc'           => 'application/vnd.sun.xml.calc',
  421.                         'sxd'           => 'application/vnd.sun.xml.draw',
  422.                         'sxg'           => 'application/vnd.sun.xml.writer.global',
  423.                         'sxi'           => 'application/vnd.sun.xml.impress',
  424.                         'sxm'           => 'application/vnd.sun.xml.math',
  425.                         'sxw'           => 'application/vnd.sun.xml.writer',
  426.                         't'                     => 'application/x-troff',
  427.                         'tar'           => 'application/x-tar',
  428.                         'tcl'           => 'application/x-tcl',
  429.                         'tex'           => 'application/x-tex',
  430.                         'texi'          => 'application/x-texinfo',
  431.                         'texinfo'       => 'application/x-texinfo',
  432.                         'tgz'           => 'application/x-gtar',
  433.                         'tif'           => 'image/tiff',
  434.                         'tiff'          => 'image/tiff',
  435.                         'tr'            => 'application/x-troff',
  436.                         'tsv'           => 'text/tab-separated-values',
  437.                         'txt'           => 'text/plain',
  438.                         'ustar'         => 'application/x-ustar',
  439.                         'vbs'           => 'text/plain', //added by skwashd - for obvious reasons
  440.                         'vcd'           => 'application/x-cdlink',
  441.                         'vcf'           => 'text/x-vcard',
  442.                         'vcs'           => 'text/calendar',
  443.                         'vfb'           => 'text/calendar',
  444.                         'vrml'          => 'model/vrml',
  445.                         'vsd'           => 'application/vnd.visio',
  446.                         'wav'           => 'audio/x-wav',
  447.                         'wax'           => 'audio/x-ms-wax',
  448.                         'wbmp'          => 'image/vnd.wap.wbmp',
  449.                         'wbxml'         => 'application/vnd.wap.wbxml',
  450.                         'wm'            => 'video/x-ms-wm',
  451.                         'wma'           => 'audio/x-ms-wma',
  452.                         'wmd'           => 'application/x-ms-wmd',
  453.                         'wml'           => 'text/vnd.wap.wml',
  454.                         'wmlc'          => 'application/vnd.wap.wmlc',
  455.                         'wmls'          => 'text/vnd.wap.wmlscript',
  456.                         'wmlsc'         => 'application/vnd.wap.wmlscriptc',
  457.                         'wmv'           => 'video/x-ms-wmv',
  458.                         'wmx'           => 'video/x-ms-wmx',
  459.                         'wmz'           => 'application/x-ms-wmz',
  460.                         'wrl'           => 'model/vrml',
  461.                         'wvx'           => 'video/x-ms-wvx',
  462.                         'xbm'           => 'image/x-xbitmap',
  463.                         'xht'           => 'application/xhtml+xml',
  464.                         'xhtml'         => 'application/xhtml+xml',
  465.                         'xls'           => 'application/vnd.ms-excel',
  466.                         'xlt'           => 'application/vnd.ms-excel',
  467.                         'xml'           => 'application/xml',
  468.                         'xpm'           => 'image/x-xpixmap',
  469.                         'xsl'           => 'text/xml',
  470.                         'xwd'           => 'image/x-xwindowdump',
  471.                         'xyz'           => 'chemical/x-xyz',
  472.                         'z'                     => 'application/x-compress',
  473.                         'zip'           => 'application/zip',
  474.        );
  475.        $type = strtolower(substr(strrchr($filename, '.'),1));
  476.        if(isset($contentType[$type])) {
  477.             $mime = $contentType[$type];
  478.        }else {
  479.             $mime = 'application/octet-stream';
  480.        }
  481.        return $mime;
  482.     }
  483. }
  484.  
  485. if(!function_exists('image_type_to_extension')){
  486.    function image_type_to_extension($imagetype) {
  487.        if(empty($imagetype)) return false;
  488.        switch($imagetype) {
  489.            case IMAGETYPE_GIF           : return '.gif';
  490.            case IMAGETYPE_JPEG          : return '.jpg';
  491.            case IMAGETYPE_PNG           : return '.png';
  492.            case IMAGETYPE_SWF           : return '.swf';
  493.            case IMAGETYPE_PSD           : return '.psd';
  494.            case IMAGETYPE_BMP           : return '.bmp';
  495.            case IMAGETYPE_TIFF_II       : return '.tiff';
  496.            case IMAGETYPE_TIFF_MM       : return '.tiff';
  497.            case IMAGETYPE_JPC           : return '.jpc';
  498.            case IMAGETYPE_JP2           : return '.jp2';
  499.            case IMAGETYPE_JPX           : return '.jpf';
  500.            case IMAGETYPE_JB2           : return '.jb2';
  501.            case IMAGETYPE_SWC           : return '.swc';
  502.            case IMAGETYPE_IFF           : return '.aiff';
  503.            case IMAGETYPE_WBMP          : return '.wbmp';
  504.            case IMAGETYPE_XBM           : return '.xbm';
  505.            default                      : return false;
  506.        }
  507.    }
  508.  
  509. }

回复 "ThinkPHP Http工具类(用于远程采集 远程下载)"

这儿你可以回复上面这条便签

captcha