2015-11-19 31 views
1

我在想如何僅在哈希存在時纔將哈希添加到圖像才能顯示圖像?如何將哈希添加到圖像以僅在存在哈希時才顯示圖像

下面是一個現有示例,其中該邏輯被實現http://193.0.171.27/13/80/98/1504890831/1531993942_square.jpg?hash=pPGpdsy8NJK1w0sq04Xjzw&expires=64060578000

上述的圖像顯示僅當散列存在於URL否則圖像是被禁止的。

有人知道該怎麼做嗎?

+0

當然你需要在value ... else之前加上這個名字無效的 – Andrew

+0

@Andrew,以及如何用php做到這一點? – oxyd

+0

...和.htaccess? – starkeen

回答

2

嗯,我看到兩種可能,你可以重寫所有的圖像鏈接,並從PHP服務它,比如像這樣:

前:

<img src="yourimagefolder/1531993942_square.jpg" /> 

後:

<img src="/getimages.php?n=1531993942_square.jpg&hash=somehash" /> 

所以你可以問問哈希是否設置和有效,然後通過PHP返回圖像,在這裏你會發現一些例子:fpassthru()。如果這是您想要的解決方案,則必須將.htaccess文件添加到您的映像目錄,因此沒有人可以直接訪問映像。

的.htaccess

Deny from all 

其他的解決辦法是把鏈接它們是如何做一個重寫與.htaccess,你會發現這裏的一些信息:

示例(如何可以工作):

文件樹

public_html 
    |--images 
     |-- example.jpg 
     |-- .htaccess 
     |-- image.php 
    |-- file that include the images 
    |-- some other files 
    |-- .... 

的.htaccess

RewriteEngine on 
RewriteRule (.*?\.jpe?g|png|gif|ico|bmp)$ image.php?image=$1&%{QUERY_STRING} [L,NC] 

image.ph p

$serveFile = false; 
if(isset($_GET["image"]) && isset($_GET["hash"])) { 
    // check hash, just for example used md5 
    $image = trim($_GET["image"]); 
    $file = dirname(__FILE__).'/'.$image; 
    $imagehash = md5($image); 

    if($imagehash === trim($_GET["hash"]) && file_exists($file)) { 
     // serve the file 
     $serveFile = true; 
    } 
} 

if($serveFile) { 
    // BEWARE you have to send the right header, 
    // maybe create an array with the content types for extensions 
    // or get a mime type function which returns this i.e.:image/jpg or some other type 
    header("Content-Type: image/jpg"); 
    header("Content-Length: " . filesize($file)); 
    readfile($file); 
// exit; 
} else { 
    // just sends a header, maybe you have to output a 403 page 
    header('HTTP/1.0 403 Forbidden'); 
    // here you can include your own 403 page 
    // include "/path/to/my/403.html"; 
    exit; 
} 

您應該調整.htaccess您的需求。

+0

關於重寫所有圖像並通過php提供服務,我想這對服務器來說太重了,特別是如果圖像大小很大,而且我有數百萬的圖像..我的意思是關於我提到的現有示例的問題。正如你所看到的,他們正在使用直接路徑到JPG而無需使用PHP。而這個問題 - 他們如何做到這一點? – oxyd

+0

那麼你必須去htacces的方式,因爲有人需要驗證給定的哈希,這隻能用腳本來完成,我認爲這是一個PHP腳本案例 – swidmann

+0

,你知道偶然任何PHP函數如何執行驗證以及如何提供圖像? – oxyd