0
0
PHPprogramming~30 mins

$_FILES for file uploads in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling File Uploads with $_FILES in PHP
📖 Scenario: You are building a simple web page where users can upload a profile picture. You want to learn how PHP handles uploaded files using the $_FILES superglobal.
🎯 Goal: Create a PHP script that accepts a file upload from an HTML form, accesses the uploaded file information using $_FILES, and displays the original file name and file size.
📋 What You'll Learn
Create an HTML form with a file input named profile_pic and method POST with enctype="multipart/form-data".
Create a PHP script that accesses the uploaded file data using $_FILES['profile_pic'].
Extract the original file name and file size from $_FILES['profile_pic'].
Display the file name and size in bytes on the page.
💡 Why This Matters
🌍 Real World
File uploads are common on websites for profile pictures, documents, or other media. Understanding <code>$_FILES</code> helps you handle these uploads safely and effectively.
💼 Career
Many web developer jobs require handling file uploads securely. Knowing how to use <code>$_FILES</code> is essential for backend PHP development.
Progress0 / 4 steps
1
Create the HTML form for file upload
Write the HTML code to create a form with method="POST" and enctype="multipart/form-data". Inside the form, add a file input with the name profile_pic and a submit button labeled Upload.
PHP
Need a hint?

Remember to set enctype="multipart/form-data" on the form to allow file uploads.

2
Check if a file was uploaded
In PHP, create an if statement that checks if $_FILES['profile_pic']['error'] is equal to UPLOAD_ERR_OK to confirm a file was uploaded without errors.
PHP
Need a hint?

Use isset($_FILES['profile_pic']) to check if the file input exists and compare the error code to UPLOAD_ERR_OK.

3
Extract the uploaded file's name and size
Inside the if block, create two variables: $fileName to store $_FILES['profile_pic']['name'] and $fileSize to store $_FILES['profile_pic']['size'].
PHP
Need a hint?

Use the name and size keys inside $_FILES['profile_pic'] to get the original file name and size in bytes.

4
Display the uploaded file's name and size
Add echo statements inside the if block to print the file name and file size in bytes in this format: File name: [file name] and File size: [file size] bytes.
PHP
Need a hint?

Use echo to print the file name and size with a line break between them.