move_uploaded_file()
The move_uploaded_file() function is a built-in PHP function that moves an uploaded file to a new location. This function takes two parameters: the temporary
What is the move_uploaded_file() Function?
The move_uploaded_file() function is a built-in PHP function that moves an uploaded file to a new location. Note: This function only works with files that were uploaded via HTTP POST. This function takes two parameters: the temporary name of the file and the destination path.
Here's the basic syntax of the move_uploaded_file() function:
The PHP syntax of move_uploaded_file()
move_uploaded_file(<temp_filename>, <destination_path>);Where <temp_filename> is the temporary name of the uploaded file, and <destination_path> is the path to the new location.
How to Use the move_uploaded_file() Function?
Using the move_uploaded_file() function is straightforward. Here are the steps to follow:
- Verify the file upload succeeded by checking
$_FILES['file']['error']. - Specify the destination path for the file.
- Call the
move_uploaded_file()function, passing in the temporary filename and the destination path.
Here's an example code snippet that demonstrates how to use the move_uploaded_file() function:
How to Use the move_uploaded_file() Function?
<?php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$uploaded_file = $_FILES['file']['tmp_name'];
$destination_path = '/path/to/new/location/' . basename($_FILES['file']['name']);
if (move_uploaded_file($uploaded_file, $destination_path)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
} else {
echo "File upload failed.";
}In this example, we first verify that the upload succeeded using $_FILES['file']['error']. We then specify the destination path for the file and use basename() to safely extract the filename and prevent path traversal vulnerabilities. Finally, we use the move_uploaded_file() function to move the uploaded file to the new location. If the file is moved successfully, we print out a success message. If there is an error moving the file, we print out an error message.
Conclusion
The move_uploaded_file() function is a useful tool in PHP for moving uploaded files to a new location. By following the steps outlined in this guide, you can easily use the move_uploaded_file() function in your PHP projects to move uploaded files to specific locations. We hope this guide has been helpful.
Practice
What is the correct usage of the move_uploaded_file() function in PHP?