move_uploaded_file
Moves a file uploaded through a form to its permanent place.
Syntax
move_uploaded_file(string $from, string $to): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $from | string | The temporary path from `$_FILES['…']['tmp_name']`. |
| $to | string | Where to save the file. |
Return value
bool`true` on success; `false` if the file was not uploaded through a form.
Examples
Saving an uploaded image:
<?php
// upload.php
$upload = $_FILES['avatar'];
if ($upload['error'] === UPLOAD_ERR_OK) {
$extension = strtolower(pathinfo($upload['name'], PATHINFO_EXTENSION));
$name = bin2hex(random_bytes(16)) . '.' . $extension;
move_uploaded_file($upload['tmp_name'], __DIR__ . '/uploads/' . $name);
}Notes
Always create the file name yourself and check the extension against an allow-list: a visitor's name may turn out to be shell.php.
See also
- pathinfo — Splits a path into parts: the folder, the name and the extension.
- is_file — Checks that a path exists and is a file rather than a folder.
- random_bytes — Returns cryptographically secure random bytes.
Related recipes
In the tutorial
- File uploads — How to accept a file from a user in PHP — the form, the $_FILES array, checking the size and type, saving safely.