0
0
PHPprogramming~30 mins

File upload security risks in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
File Upload Security Risks
📖 Scenario: You are building a simple PHP web application that allows users to upload image files. However, you want to make sure the file upload is secure and does not allow harmful files to be uploaded.
🎯 Goal: Create a PHP script that securely handles file uploads by checking the file type and size before saving it to the server.
📋 What You'll Learn
Create an array called allowed_types with the values 'image/jpeg', 'image/png', and 'image/gif'
Create a variable called max_size and set it to 2000000 (2MB)
Write code to check if the uploaded file's MIME type is in allowed_types and its size is less than max_size
If the file passes checks, move it to the uploads/ folder and print 'Upload successful'
If the file fails checks, print 'Upload failed: Invalid file type or size'
💡 Why This Matters
🌍 Real World
Websites often allow users to upload images or documents. Ensuring these files are safe prevents hackers from uploading harmful scripts.
💼 Career
Web developers must secure file uploads to protect websites and users from security risks like malware or unauthorized access.
Progress0 / 4 steps
1
Setup allowed file types
Create an array called allowed_types with these exact values: 'image/jpeg', 'image/png', and 'image/gif'.
PHP
Need a hint?

Use square brackets [] to create the array with the exact strings inside.

2
Set maximum file size
Create a variable called max_size and set it to 2000000 (which means 2 megabytes).
PHP
Need a hint?

Just assign the number 2000000 to the variable $max_size.

3
Check file type and size
Write an if statement that checks if $_FILES['userfile']['type'] is in $allowed_types and $_FILES['userfile']['size'] is less than $max_size.
PHP
Need a hint?

Use in_array() to check if the file type is allowed and compare the size with $max_size.

4
Move file and print result
Inside the if block, move the uploaded file from $_FILES['userfile']['tmp_name'] to 'uploads/' . $_FILES['userfile']['name'] using move_uploaded_file(). Then print 'Upload successful'. In the else block, print 'Upload failed: Invalid file type or size'.
PHP
Need a hint?

Use move_uploaded_file() to save the file and print() to show messages.