2015-10-22 160 views
0

我單擊鏈接時將圖像路徑作爲GET參數傳遞,但爲了安全起見,我需要檢查它是否爲圖像。Laravel檢查圖像路徑字符串是否爲圖像

當我嘗試這個代碼,其中$fileName是「15612.jpg」:

$fileName = $_GET['fileName']; 

$image = array('file' => File::get('unverified-images/'.$fileName)); 
$rules = array('file' => 'image'); 
$validator = Validator::make($image, $rules); 

if ($validator->fails()) { 
    Session::flash('error', 'Not an image'); 
    return Redirect::to('controlpanel'); 
} 

所有.jpg文件我已經測試給予「不是一個形象」,但是當我試圖用一個txt文件它不會給出錯誤,這是爲什麼?我在猜測我做錯了什麼,因爲驗證器在不是圖像時應該失敗,對吧?

我知道驗證程序需要Input::file()而不是File::get(),但如果我不使用表單,該如何使用?

+0

,您應該使用symfony中的http請求的實例,在您的Laravel項目。永遠不要使用$ _GET或$ _POST檢索數據。您可以將請求實例注入到您的控制器中,如下所示: '公共函數存儲(\ Illuminate \ Http \ Request $ request)' 也可以使用'use'語句註冊illuminate \ http \ request類。 你也可以在你的控制器做到這一點: '公共職能店($申請要求) {$ 這 - >的validate($請求,[ '形象'=> '需要|形象']); }' – everytimeicob

回答

5

這可能是避免了驗證,並做自我檢查的情況下,所以你可以這樣做:

$allowedMimeTypes = ['image/jpeg','image/gif','image/png','image/bmp','image/svg+xml']; 
$contentType = mime_content_type('path/to/image'); 

if(! in_array($contentType, $allowedMimeTypes)){ 
    Session::flash('error', 'Not an image'); 
    return Redirect::to('controlpanel'); 
} 
+0

或此 https://stackoverflow.com/a/48799600/4255747 –