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.
HTML Form for File Upload
Important:
enctype="multipart/form-data"→ required for file uploadsmethod="post"→ must be POST
PHP Script to Handle File Upload (upload.php)
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 |
Security Tips
Validate file type – avoid uploading executable files.
Limit file size – prevent server overload.
Rename files – avoid overwriting existing files.
Store outside web root – for sensitive files.
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
$_FILESsuperglobal 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.
