How can PHP developers handle image uploads securely without using an HTML upload form?

To handle image uploads securely without using an HTML upload form, PHP developers can create a script that accepts image files through a POST request, verifies the file type and size, generates a unique filename, and moves the uploaded file to a secure directory on the server. This approach ensures that only valid image files are accepted and stored securely.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $uploadDir = 'uploads/';
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $maxFileSize = 5 * 1024 * 1024; // 5MB

    if (in_array($_FILES['image']['type'], $allowedTypes) && $_FILES['image']['size'] <= $maxFileSize) {
        $filename = uniqid() . '_' . $_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $filename);
        echo 'Image uploaded successfully!';
    } else {
        echo 'Invalid file type or size. Please upload a valid image file.';
    }
}
?>