How to upload a file to the server
Short answer
The form needs the enctype attribute, and move_uploaded_file() saves the file:
<?php
// upload.php
$file = $_FILES['avatar'] ?? null;
if ($file && $file['error'] === UPLOAD_ERR_OK) {
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$name = bin2hex(random_bytes(16)) . '.' . $extension;
move_uploaded_file($file['tmp_name'], __DIR__ . '/uploads/' . $name);
echo 'Saved as ' . $name;
}The form
Without enctype="multipart/form-data" the file never reaches the server: <form method="post" enctype="multipart/form-data"> and an <input type="file" name="avatar"> field.
Checks
Check the size and the extension against an allow-list:
<?php
// upload.php
$file = $_FILES['avatar'];
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($file['size'] > 2 * 1024 * 1024) {
exit('The file is larger than 2 MB');
}
if (!in_array($extension, ['jpg', 'png', 'webp'], true)) {
exit('Only images are allowed');
}Functions used in this recipe
- move_uploaded_file — Moves a file uploaded through a form to its permanent place.
- pathinfo — Splits a path into parts: the folder, the name and the extension.
- random_bytes — Returns cryptographically secure random bytes.