」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用“in_array()”在 PHP 中驗證上傳的檔案類型?

如何使用“in_array()”在 PHP 中驗證上傳的檔案類型?

發佈於2024-11-26
瀏覽:423

How to Validate Uploaded File Types in PHP with `in_array()`?

使用 PHP 上傳指定的文件類型

在 Web 應用程式中,允許使用者上傳文件需要仔細考慮安全性和內容驗證。當您想要限制上傳特定檔案類型時,PHP 透過 in_array() 函數提供了解決方案。

問題:

您希望在中建立 if 語句PHP 驗證上傳的檔案並僅允許以下類型的檔案:jpg、gif 和 pdf。下面的程式碼需要適當地建構 if 語句。

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

if(/*$file_type is anything other than jpg, gif, or pdf*/) {
  $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
}

解決方案:

為了確保上傳的文件符合您的規範,請建立一個允許的文件類型數組,並使用in_array() 來確定上傳文件的mimetype 是否為包含在陣列中。

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

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

透過將檔案類型與預先定義的允許類型清單進行比較,此修訂後的 if 語句可有效防止上傳不合規檔案。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3