How to Move Uploaded File in PHP

Move uploaded file to its destination directory is very important via back-end. PHP provides move_uploaded_file() method by default to move uploaded file.

How to use move_uploaded_file() method

In PHP uploaded file first goes to temp folder of server. The server discards uploaded files from the temp folder if not moved after uploading.

So, moving the uploaded files from temp to the destination folder is very important. Here, we have to use the move_uploaded_file() function of core PHP to move uploaded files to the destination directory.

We just have to pass a temporary location and destination directory of an uploaded file in move_uploaded_file() method.

Syntax

move_uploaded_file("TEMPORARY_PATH", "DESTINATION_PATH");

Note: Temporary location can be found by $_FILES[‘field_name’][‘tmp_name’], where field_name should be file field name in the form and tmp_name should be changed.

Read More: How to Upload File in PHP

Example

<?php  

// Destinaiton path
$destination_path = "YOUR_PATH";

// Concatenating uploaded file name with destination path
$destination_path = $destination_path.basename($_FILES['file']['name']);   

// Moving uploaded file
if(move_uploaded_file($_FILES['file']['tmp_name'], $destination_path)) {
	echo "File moved successfully.";  
} else{
	echo "Error, file not moved.";  
}
?>

Explanation

In the above example, we first defined a variable containing the destination folder. After that, we found the file name of an uploaded file with basename() method and concatenated it with the destination path. Finally, we moved the uploaded file with the move_uploaded_file() method.

Conclusion

Now we have understood the complete usage of move_uploaded_file function. Even more, we found how to get the filename of an uploaded file with basename() method.

Enjoy Coding 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *