PHP File Upload

PHP Tutorial

PHP File Upload Tutorial

PHP allows users to upload files from a web form to the server. File uploads are commonly used for images, documents, and user data.


 HTML Form for File Upload


 

Important:

  • enctype="multipart/form-data" → required for file uploads

  • method="post" → must be POST


PHP Script to Handle File Upload (upload.php)


 


 Key Functions & Superglobals

Function / VariablePurpose
$_FILES['myfile']Holds uploaded file info
$_FILES['myfile']['name']Original file name
$_FILES['myfile']['tmp_name']Temporary file location on server
$_FILES['myfile']['size']File size in bytes
$_FILES['myfile']['type']MIME type
move_uploaded_file()Move the uploaded file to the desired folder
is_dir()Check if a folder exists
mkdir()Create a folder

 Security Tips

  1. Validate file type – avoid uploading executable files.

  2. Limit file size – prevent server overload.

  3. Rename files – avoid overwriting existing files.

  4. Store outside web root – for sensitive files.

  5. Use move_uploaded_file() – ensures proper file handling.


 Optional: Rename Uploaded File


 

 Prevents overwriting files with the same name.


 Summary

  • Use HTML form with enctype="multipart/form-data".

  • Use $_FILES superglobal to access file info.

  • Use move_uploaded_file() to save the file.

  • Always validate type and size for security.

  • Optionally, rename files to avoid conflicts.

You may also like...