PHP File Upload Example

Here is an example of a PHP file upload script:

<?php

// Set the directory where the uploaded file will be saved

$upload_dir = 'uploads/';


// Check if the file was uploaded

if (isset($_FILES['fileToUpload'])) {


    // Check if the file is an image

    if ($_FILES['fileToUpload']['type'] == 'image/jpeg' || $_FILES['fileToUpload']['type'] == 'image/png') {


        // Get the file name and extension

        $file_name = $_FILES['fileToUpload']['name'];

        $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);


        // Create a new file name for the uploaded file

        $new_file_name = uniqid() . '.' . $file_extension;


        // Move the uploaded file to the upload directory

        move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $upload_dir . $new_file_name);


        // Success!

        echo "File uploaded successfully!";

    } else {

        // Error! The file is not an image

        echo "File is not an image.";

    }

} else {

    // Error! No file was uploaded

    echo "No file was uploaded.";

}

?>


This script will first check if the file was uploaded. If it was, the script will check if the file is an image. If it is, the script will create a new file name for the uploaded file and move it to the upload directory. Finally, the script will display a message indicating whether or not the file upload was successful.


Here is an example of the HTML form that can be used with this script:


HTML

<form action="upload.php" method="post" enctype="multipart/form-data">

    <input type="file" name="fileToUpload">

    <input type="submit" value="Upload">

</form>


When the user clicks the "Upload" button, the file will be uploaded to the server and the PHP script will be executed.

No comments:

Post a Comment