How can PHP scripts be modified to automatically delete old images when a new image is uploaded by a user?

When a new image is uploaded by a user, we can modify the PHP script to automatically delete old images by checking the upload directory for existing images before moving the new image. If old images are found, they can be deleted before moving the new image to the directory. This ensures that only the most recent image is kept in the upload directory.

// Check for existing images in the upload directory
$uploadDir = 'uploads/';
$files = glob($uploadDir . '*');
foreach ($files as $file) {
    if (is_file($file)) {
        unlink($file); // Delete old image
    }
}

// Move the new image to the upload directory
$targetFile = $uploadDir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile);
echo "Image uploaded successfully!";