2015-04-06 55 views
0

我有一個url像這樣如何從功能file_get_content()

$url ="www.domain.com/image.php?id=123&idlocation=987&number=01"; 

以前我是使用下面的代碼

$img_details= pathinfo($url); 

得到擴展圖像extention但是,這是不行的因爲url還有其他變量。所以在這種情況下如何獲取圖像名稱和擴展名。

我知道我應該使用

$contenido = file_get_contents($url); 

先下載該文件,但不知道如何從這個

由於獲得的文件名/擴展時提前

回答

0
$ch = curl_init(); 
$url = 'http://www.domain.com/image.php?id=123&idlocation=987&number=01'; 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_NOBODY, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

$results = split("\n", trim(curl_exec($ch))); 
foreach($results as $line) { 
     if (strtok($line, ':') == 'Content-Type') { 
       $parts = explode(":", $line); 
       echo trim($parts[1]); 
     } 
} 

返回:圖像/ PNG

已經回答:Get mime type of external file using cURL and php

+0

難道還有比使用curl任何其他方式?,就像使用下載的變量get_file_content(),然後其他一些功能得到擴展 – Vikram 2015-04-06 08:47:19

+0

這在大多數情況下都能正常工作,但仍然依賴服務器返回正確的內容類型頭文件,而不是像application/octet-stream那樣。如果圖像已被下載了它可能更容易檢查的前幾個字節 - 爲examle JPEG總是使用0xFF 0xD8開始,GIF與GIF等開始 – 2015-04-06 13:51:09

+0

你可以嘗試的file_get_contents後解析$ http_response_header變量()。這將與從cURL解析頭文件相同。我承認我從來沒有使用過這種方法,因爲cURL給了更多的靈活性,但根據http://php.net/manual/en/reserved.variables.httpresponseheader.php它應該工作 – 2015-04-07 09:10:10

0

以上答案同時注重MIME類型,他們將在大多數情況下,他們都需要額外的資源使用 - 無論是第二網絡調用來獲取mime類型或多個磁盤讀取/寫入文件保存到磁盤並使用exif-imagetype函數。而且兩者都不會返回作爲問題一部分的文件名。這裏是一個使用curl的下載函數,它將返回一個下載的文件作爲名稱,MIME類型和內容的數組。另外,如果可能的話,它會嘗試從URL中獲取名稱。

使用範例

$file=downloadfile($url); 
echo "Name: ".$file["name"]."<br>"; 
echo "Type: ".$file["mimetype"]."<br>"; 

代碼

function downloadfile($url){ 
    global $headers; 

    $headers=array(); 
    $file=array("content"=>"","mimetype"=>"","name"=>""); 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'readHeaders'); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $file["content"]=curl_exec($ch); 
    if(sizeof($headers)){ 
    foreach($headers as $header){ 
     if(!strncasecmp($header,'content-type:',13)){ 
     $file["mimetype"]=trim(substr($header,13)); 
     } 
     elseif(!strncasecmp($header,'content-disposition:',20)){ 
     $file["name"]=trim(substr(strstr($header,'filename='),9)); 
     } 
    } 
    } 
    if(!$file["name"]){ 
    $query=strpos("?",$url); 
    $file["name"]=basename(substr($url,0,($query?$query:strlen($url)))); 
    } 
    unset($headers); 
    return $file; 
} 
function readHeaders($ch, $header) { 
    global $headers; 
    array_push($headers, $header); 
    return strlen($header); 
}