0
0
PHPprogramming~5 mins

$_FILES for file uploads in PHP

Choose your learning style9 modes available
Introduction

$_FILES helps you get information about files users upload through a form. It makes handling uploads easy.

When you want users to upload profile pictures on your website.
When you need to let users submit documents or PDFs.
When building a form that accepts multiple images for a gallery.
When you want to save uploaded files on your server.
When you want to check the size or type of an uploaded file before saving.
Syntax
PHP
$_FILES['input_name']['property']

input_name is the name attribute of the file input in your HTML form.

property can be name, type, tmp_name, error, or size.

Examples
Gets the original name of the uploaded file from the input named 'photo'.
PHP
$_FILES['photo']['name']
Gets the size in bytes of the uploaded file from the input named 'document'.
PHP
$_FILES['document']['size']
Gets the temporary file path where PHP stored the uploaded file before you move it.
PHP
$_FILES['avatar']['tmp_name']
Sample Program

This program shows a simple file upload form. When you pick a file and submit, it prints the file name and size if the upload worked.

PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['myfile']) && $_FILES['myfile']['error'] === 0) {
        $filename = $_FILES['myfile']['name'];
        $filesize = $_FILES['myfile']['size'];
        echo "File uploaded: $filename<br>";
        echo "Size: $filesize bytes<br>";
    } else {
        echo "No file uploaded or there was an error.";
    }
}
?>

<form method="post" enctype="multipart/form-data">
  <label for="myfile">Choose a file:</label>
  <input type="file" name="myfile" id="myfile">
  <button type="submit">Upload</button>
</form>
OutputSuccess
Important Notes

Always use enctype="multipart/form-data" in your form tag to allow file uploads.

Check $_FILES['input_name']['error'] to make sure the upload succeeded before using the file.

Files are stored temporarily on the server. Use move_uploaded_file() to save them permanently.

Summary

$_FILES holds info about uploaded files from a form.

Use the file input's name to access its data in $_FILES.

Check for errors and file size before saving the file.