php
2013-02-09 52 views -1 likes 
-1

我正在創建一個腳本,允許用戶上傳圖像,但現在我想包括一個簡單的if語句,它只接受gif和png。這是我的代碼,但它似乎沒有按照它的方式工作。如果語句過濾文件擴展名

#extention filter 
$allowed = array("image/gif","image/png"); 
if(!in_array($files,$allowed)){ 
$error_message = 'Only jpg, gif, and pdf files are allowed.'; 
    $error = 'yes'; 
    echo $error_message; 
    exit(); 
} #extention 

回答

4
$filename=$_FILE['name']['filename_in_html']; //you can change this with your filename 
    $allowed='png,jpg'; //which file types are allowed seperated by comma 

    $extension_allowed= explode(',', $allowed); 
    $file_extension= pathinfo($filename, PATHINFO_EXTENSION); 
    if(array_search($file_extension, $extension_allowed)) 
    { 
     echo "$extension_allowed allowed for uploading file"; 
    } 
    else 
    { 
     echo "$extension_allowed is not allowed for uploading file"; 
    } 
+0

你的代碼工作4我100%謝謝男人 – humphrey 2013-02-10 07:10:07

0
$path_parts = pathinfo('/path/emptyextension.'); 
var_dump($path_parts['extension']); 

這將返回精確的擴展,您可以根據需要進行比較。

2
$file_type = $_FILES['name']['type']; //returns the mimetype 

$allowed = array("image/png", "image/gif", "application/pdf"); 
if(!in_array($file_type, $allowed)) { 
    $error_message = 'Only png, gif files are allowed.'; 
    $error = 'yes'; 
} 

希望它能幫助解決問題。

相關問題