Are there any best practices for automating the process of uploading images to a website using PHP?

When automating the process of uploading images to a website using PHP, it is important to follow best practices to ensure security and efficiency. One common approach is to use a form to allow users to select and upload images, validate the file type and size, generate a unique filename to prevent overwriting existing files, and move the uploaded file to a designated directory on the server.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
    $targetDir = "uploads/";
    $targetFile = $targetDir . uniqid() . "_" . basename($_FILES["image"]["name"]);
    
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
        echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="Upload">
</form>