Home  >  Article  >  Database  >  How to Restrict File Types and Size in PHP File Uploads?

How to Restrict File Types and Size in PHP File Uploads?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 04:58:02771browse

How to Restrict File Types and Size in PHP File Uploads?

PHP File Upload: Efficiently Restricting File Types and Size

In PHP, controlling file uploads and ensuring the acceptance of specific file types is crucial. One user recently encountered issues with their existing validation code:

<code class="php">//check file extension and size
$resume= ($_FILES['resume']['name']);
$reference= ($_FILES['reference']['name']);
$ext = strrchr($resume, ".");
$ext1 = strrchr($reference, ".");
if (!(($_FILES["resume"]["type"] == "application/doc")
|| ($_FILES["resume"]["type"] == "application/docx")
|| ($_FILES["resume"]["type"] == "application/pdf" ))
&& (($_FILES["reference"]["type"] == "application/doc")
|| ($_FILES["reference"]["type"] == "application/docx")
|| ($_FILES["reference"]["type"] == "application/pdf"))
&& (($ext == ".pdf") || ($ext == ".doc") || ($ext == ".docx"))
&& (($ext1 == ".pdf") || ($ext1 == ".doc") || ($ext1 == ".docx"))
&&  ($_FILES["resume"]["size"] < 400000) //accept upto 500 kb
&&  ($_FILES["reference"]["size"] < 400000)) {

//stop user
} else {
// allow files to upload
}</code>

According to the user, this code allowed unauthorized file types (e.g., TXT) to pass through and did not enforce the size limit.

Solution: Relying on MIME Types and Proper Size Checks

To address these issues, a more robust approach is recommended:

<code class="php">function allowed_file(){

//Allowed mime-type files
$allowed = array('application/doc', 'application/pdf', 'another/type');

//Validate uploaded file type
if(in_array($_FILES['resume']['type'], $allowed) AND in_array($_FILES['reference']['type'], $allowed)){

//Check file size
if($_FILES["resume"]["size"] < 400000 AND $_FILES["reference"]["size"] < 400000 ){

//File types and size are accepted, proceed with file processing
}
}
}</code>

Explanation:

This improved code utilizes MIME (Multipurpose Internet Mail Extension) types rather than file extensions. MIME types accurately represent file formats and are less prone to manipulation. Additionally, it checks the file size independently for both resume and reference files, ensuring that the limit is enforced.

The above is the detailed content of How to Restrict File Types and Size in PHP File Uploads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn