2016-10-27 86 views
-1

如何確定URL是否爲ZIP,但首先不要下載整個URL,因爲它可能太大?我能以某種方式得到幾個字節並檢查ZIP標頭嗎?檢查URL是否爲郵政編碼

+2

檢查zip標頭是最安全的。快速/髒將執行HEAD請求並查看內容類型是否爲應用程序/ zip –

+0

您可以使用'CURLOPT_RANGE'來指定要下載的字節範圍。因此,請指定類似「0-64」的內容來獲取文件的前64個字節。但請參閱http://stackoverflow.com/questions/6048158/alternative-to-curlopt-range-to-grab-a-specific-section – Barmar

回答

1

我修改了從this answer開始的代碼,而不是從響應中讀取4個字節(使用範圍,或者在讀取4個字節後通過中止),然後查看4個字節是否與zip魔頭匹配。

試一試,讓我知道結果。如果curl請求由於某種原因失敗,您可能需要添加一些錯誤檢查以查看文件的類型是否無法確定。

<?php 

/** 
* Try to determine if a remote file is a zip by making an HTTP request for 
* a byte range or aborting the transfer after reading 4 bytes. 
* 
* @return bool true if the remote file is a zip, false otherwise 
*/ 
function isRemoteFileZip($url) 
{ 
    $ch = curl_init($url); 

    $headers = array(
     'Range: bytes=0-4', 
     'Connection: close', 
    ); 

    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2450.0 Iron/46.0.2450.0'); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_VERBOSE, 0); // set to 1 to debug 
    curl_setopt($ch, CURLOPT_STDERR, fopen('php://output', 'r')); 

    $header = ''; 

    // write function that receives data from the response 
    // aborts the transfer after reading 4 bytes of data 
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) use(&$header) { 
     $header .= $data; 

     if (strlen($header) < 4) return strlen($data); 

     return 0; // abort transfer 
    }); 

    $result = curl_exec($ch); 
    $info = curl_getinfo($ch); 

    // check for the zip magic header, return true if match, false otherwise 
    return preg_match('/^PK(?:\x03\x04|\x05\x06|0x07\x08)/', $header); 
} 

var_dump(isRemoteFileZip('https://example.com/file.zip')); 
var_dump(isRemoteFileZip('https://example.com/logo.png'));