How To Move File In Php

In this blog post, we will learn how to move files in PHP using the move_uploaded_file() function. This function is mainly used to move uploaded files from the temporary folder to a desired location on the server.

Step 1: Create an HTML Form

First, we need to create an HTML form with a file input field that allows users to browse and select a file from their local filesystem. The form should have the enctype=”multipart/form-data” attribute to handle file uploads correctly.

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select a file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

Step 2: Process the File Upload in PHP

Next, create a new file named upload.php to handle the file upload process in PHP. This file will contain the code to move the uploaded file from the temporary folder to the desired location on the server.

First, we need to check if the file upload button has been clicked:

<?php
if (isset($_POST['submit'])) {
    // File upload processing code here
}
?>

Now, we will use the move_uploaded_file() function to move the uploaded file to a specific directory. This function takes two parameters: the temporary file location and the desired file location.

<?php
if (isset($_POST['submit'])) {
    // Set the target directory and file name
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

    // Move the uploaded file to the target directory
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

In the above code snippet, we define a target directory named uploads/ and set the target file name. Then, we use the move_uploaded_file() function to move the uploaded file from its temporary location to the desired location.

Conclusion

In this blog post, we learned how to move files in PHP using the move_uploaded_file() function by creating an HTML form and handling the file upload process in a separate PHP file. This is a simple and effective way to manage file uploads and store uploaded files on your server.