309 of 410 menu

The move_uploaded_file Function

The move_uploaded_file function moves an uploaded file from the temporary directory to the specified location. The first parameter of the function accepts the temporary filename, and the second one - the path to save the file.

Syntax

move_uploaded_file(string $from, string $to): bool

Example

Moving an uploaded file to the uploads folder:

<?php $temp = $_FILES['file']['tmp_name']; $name = $_FILES['file']['name']; if (move_uploaded_file($temp, 'uploads/' . $name)) { echo 'file uploaded successfully'; } else { echo 'upload failed'; } ?>

Example

Checking for successful file upload before moving:

<?php $temp = $_FILES['file']['tmp_name']; $name = $_FILES['file']['name']; if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { $res = move_uploaded_file($temp, 'files/' . uniqid() . '_' . $name); echo $res ? 'Success' : 'Error'; } else { echo 'Upload error: ' . $_FILES['file']['error']; } ?>

Example

Creating a unique filename when moving:

<?php $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); $newName = 'userfile_' . time() . '.' . $ext; $res = move_uploaded_file($_FILES['file']['tmp_name'], 'storage/' . $newName); var_dump($res); ?>

See Also

  • the copy function,
    which copies a file
  • the rename function,
    which renames a file
  • the is_uploaded_file function,
    which checks an uploaded file
byenru