How to Upload Files in PHP?

To upload files in PHP you will need a HTML form with necessary attributes for file uploads and handling the uploaded files on the server side. Here’s a step-by-step guide on how to upload files in PHP :

1. Create the HTML Form

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Choose File:</label>
        <input type="file" name="file" id="file" required>
        <button type="submit" name="submit">Upload</button>
    </form>
</body>
</html>

2. Create the PHP Script (upload.php)

PHP
<?php
// Check if the form is submitted
if (isset($_POST['submit'])) {
    // Define the target directory to store uploaded files
    $targetDir = "uploads/";

    // Create the target directory if it doesn't exist
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    // Get the uploaded file's details
    $fileName = basename($_FILES['file']['name']);
    $targetFilePath = $targetDir . $fileName;
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

    // Check if the file is a valid image
    $allowTypes = array('jpg', 'jpeg', 'png', 'gif');
    if (in_array($fileType, $allowTypes)) {
        // Upload the file to the specified directory
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)) {
            echo "The file $fileName has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    } else {
        echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
    }
}
?>

Leave a Reply

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