获取远程文件类型 for PHP

PHP 内部有函数可以得到远程文件类型,但是需要其它库的支持,或者是更改PHP的环境,下面有使用fsockopen函数来实现获取远程文件类型,代码如下:
<?php
class RemoteFile{
    var $url;
    var $host;
    var $path;
   
    function  __construct($url) {
        $this->url = $url;
        $this->parse();
    }
    function parse(){
 $matches = parse_url($this->url);
 $this->host = $matches['host'];
 $this->path = isset($matches['path'])?$matches['path']:'';
    }
    function tag_substr($string,$start_string,$end_string){
 $start_pos = strpos($string,$start_string);//查看是否有起始标记
 if($start_pos === false){
            return '';
 }
 $start_pos+=strlen($start_string);
 $end_pos=strpos($string,$end_string,$start_pos);//查看是否有结束标记
 if($end_pos===false){
            return substr($string,$start_pos);
 }
 return substr($string,$start_pos,$end_pos-$start_pos);
    }
   
    function GetFileType(){
        $header = "HEAD ".$this->path." HTTP/1.1\r\n";
        $header.= "Host: ".$this->host."\r\n";
        $header.= "Connection: Close\r\n\r\n";
        $fp = @fsockopen($this->host,80,$errno,$errstr);
        if($fp){
            fwrite($fp,$header);
            $html='';
            while(!feof($fp)){
                $html.=fgets($fp);
            }
            fclose($fp);
            if(strpos($html,'Content-Location:')!==false){
                $html=str_replace('Content-Location:','',$html);
            }
            $location=$this->tag_substr($html,'Location: ',"\r\n");
            if(strlen($location)>5){
                $this->url = $location;
                $this->parse();
                $type=$this->GetFileType();
            }else{
                $type=$this->tag_substr($html,"Content-Type: ","\r\n");
            }
            return $type;
        }else{
            return 'text/html';
        }
    }
}
$file = new RemoteFile('http://img1.51cto.com/group_images/group_images/125661077813.jpg');
$type = $file->GetFileType();
echo $type;
?>

你可能感兴趣的:(PHP,职场,休闲,远程文件类型,RemoteFileType)