How can PHP handle file uploads securely to prevent possible attacks?

To handle file uploads securely in PHP, you can use the following methods: 1. Validate file types and sizes to prevent malicious uploads. 2. Store uploaded files outside the web root directory to prevent direct access. 3. Use unique file names to prevent overwriting existing files.

<?php
// Check if the file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    // Validate file type and size
    $allowedTypes = array('image/jpeg', 'image/png');
    $maxFileSize = 1048576; // 1MB

    if(in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize){
        // Move the uploaded file to a secure location
        if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)){
            echo "File uploaded successfully.";
        } else {
            echo "Error uploading file.";
        }
    } else {
        echo "Invalid file type or size.";
    }
} else {
    echo "File upload error.";
}
?>