PHP File Upload

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.


1️⃣ HTML Form for File Upload


 

Important:

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

  • method="post" → must be POST


2️⃣ PHP Script to Handle File Upload (upload.php)


 


3️⃣ Key Functions & Superglobals

Function / Variable Purpose
$_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

4️⃣ 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.


5️⃣ 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *