How can one ensure the security and functionality of a PHP script for image uploading and rating?

To ensure the security and functionality of a PHP script for image uploading and rating, you should validate and sanitize user input, check file extensions and sizes, store images in a secure directory, prevent SQL injection attacks, and implement proper error handling.

<?php
// Validate and sanitize user input
$imageName = filter_var($_POST['imageName'], FILTER_SANITIZE_STRING);
$rating = filter_var($_POST['rating'], FILTER_VALIDATE_INT);

// Check file extensions and sizes
$allowedExtensions = ['jpg', 'jpeg', 'png'];
$allowedSize = 1048576; // 1MB

if(in_array(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION), $allowedExtensions) && $_FILES['image']['size'] <= $allowedSize) {
    // Store images in a secure directory
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['image']['name']);
    
    if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
        // Prevent SQL injection attacks
        $conn = new mysqli('localhost', 'username', 'password', 'database');
        $stmt = $conn->prepare("INSERT INTO images (name, rating) VALUES (?, ?)");
        $stmt->bind_param('si', $imageName, $rating);
        $stmt->execute();
        
        echo 'Image uploaded and rated successfully!';
    } else {
        echo 'Failed to upload image.';
    }
} else {
    echo 'Invalid file format or size.';
}
?>