📜  move_uploaded_file - PHP (1)

📅  最后修改于: 2023-12-03 15:32:58.157000             🧑  作者: Mango

move_uploaded_file - PHP

move_uploaded_file is a PHP function that moves an uploaded file to a new location. This function is commonly used when handling file uploading in web applications.

Syntax
bool move_uploaded_file ( string $filename , string $destination )
Parameters
  • filename: The temporary filename of the uploaded file given by the web browser.
  • destination: The destination file name. This should be a path and filename on the server where the file should be moved to.
Return Value

This function returns true if successful and false otherwise.

Example
<?php
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $filename = $file['name'];
    $tmp_name = $file['tmp_name'];
    $target_dir = 'uploads/';
    $target_file = $target_dir . basename($filename);

    if (move_uploaded_file($tmp_name, $target_file)) {
        echo 'File uploaded successfully';
    } else {
        echo 'An error occurred while uploading the file';
    }
}
?>

In this example, we first check if a file was uploaded using the isset function. We then extract the necessary information from the $_FILES global variable, including the file name and temporary file name.

Next, we define a target directory where the file should be uploaded to and concatenate it with the base name of the original file to create the destination file name. Finally, we call the move_uploaded_file function to move the uploaded file to its new location.

If the file is moved successfully, we output a success message. If an error occurs, we output an error message instead.

Conclusion

move_uploaded_file is a useful function for handling file uploads in PHP web applications. By understanding its syntax, parameters, return value, and usage, you can handle file uploads with confidence and security.