PHP
move_uploaded_file()
Learn to move the temporary file to a permanent location with move_uploaded_file().
What is move_uploaded_file()?
An uploaded file first lands in a temporary location. This path is stored in tmp_name and is deleted when the script ends. To move the file to a permanent place you use move_uploaded_file().
The function takes two parameters: the temporary path (tmp_name) and the destination. Example: move_uploaded_file($file['tmp_name'], 'uploads/photo.jpg'). It returns true on success and false on failure.
Prefer this over rename(): move_uploaded_file() first checks that the file really is an HTTP upload.
Build the destination path
When building the destination, mind two things: the folder and the file name. You usually combine a folder like uploads/ with the original name: $dest = 'uploads/' . $file['name'].
But a user may send a dangerous name like ../shell.php. So use basename() to keep only the file name: $dest = 'uploads/' . basename($file['name']). This blocks path traversal attacks.
For a unique name you can prefix with uniqid(); but first learn the basic move.
Exercise The saveUpload function
Write a saveUpload(array $file, string $dir): string function. Inside it, build the destination with $destination = $dir . '/' . basename($file['name']). Call move_uploaded_file($file['tmp_name'], $destination). Then return 'Target: ' . $destination. For testing, define $_FILES['avatar'] (name: 'profile.jpg', tmp_name: '/tmp/phpAbCd.tmp', error: 0, size: 2048) and write echo saveUpload($_FILES['avatar'], 'uploads') . "\n".
Show example solution
Inside saveUpload build $destination with basename, call move_uploaded_file and return the target.
Example solution:
<?php
// File move function
function saveUpload(array $file, string $dir): string {
$destination = $dir . '/' . basename($file['name']);
move_uploaded_file($file['tmp_name'], $destination);
return "Target: " . $destination;
}
$_FILES['avatar'] = [
'name' => 'profile.jpg',
'tmp_name' => '/tmp/phpAbCd.tmp',
'error' => 0,
'size' => 2048
];
echo saveUpload($_FILES['avatar'], 'uploads') . "\n";
Test yourself
-
Which function securely moves an uploaded file?
- rename()
- copy()
- move_uploaded_file()
- unlink()
Show answer
move_uploaded_file() — Correct. move_uploaded_file checks the upload first.
-
The move_uploaded_file call
$ok = move_uploaded_file($file['tmp_name'], ____);
Show answer
$ok = move_uploaded_file($file['tmp_name'], $destination);
-
Match the functions
- move_uploaded_file
- Moves the temp file
- basename
- Returns the file name
- is_uploaded_file
- Checks if it is an upload
- rename
- Moves any file
Next lesson: Validating file type