<?php
 
// Define the path to the upload directory
 
$targetDir = "uploads/";
 
// Make sure the upload directory exists
 
if (!file_exists($targetDir)) {
 
    mkdir($targetDir, 0777, true);
 
}
 
 
if (isset($_FILES["file"])) {
 
    // Get the file extension
 
    $fileType = strtolower(pathinfo(basename($_FILES["file"]["name"]), PATHINFO_EXTENSION));
 
    // Allowed file types
 
    $allowedTypes = ['jpg', 'png', 'jpeg', 'gif'];
 
 
    // Check if the file is an image
 
    if (in_array($fileType, $allowedTypes)) {
 
        // Generate a unique name for the file
 
        $uniqueFileName = md5(time() . rand()) . "." . $fileType;
 
        $uniqueFilePath = $targetDir . $uniqueFileName;
 
 
        // Check if file already exists
 
        if (!file_exists($uniqueFilePath)) {
 
            // Try to upload the file
 
            if (move_uploaded_file($_FILES["file"]["tmp_name"], $uniqueFilePath)) {
 
                echo "The file " . htmlspecialchars($uniqueFileName) . " has been uploaded.";
 
            } else {
 
                echo "Sorry, there was an error uploading your file.";
 
            }
 
        } else {
 
            echo "File already exists. Please try again.";
 
        }
 
    } else {
 
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
 
    }
 
} else {
 
    echo "No file was uploaded. Please try again.";
 
}
 
?>
 
 |