PHP 内部有函数可以得到远程文件类型,但是需要其它库的支持,或者是更改PHP的环境,下面有使用fsockopen函数来实现获取远程文件类型,代码如下:
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('https://img1.51cto.com/group_p_w_picpaths/group_p_w_picpaths/125661077813.jpg');
$type = $file->GetFileType();
echo $type;
?>