Are there any recommended best practices for handling file uploads in PHP?

When handling file uploads in PHP, it is important to validate and sanitize the file before storing it on the server. This includes checking the file type, size, and ensuring it does not overwrite existing files. It is also recommended to store uploaded files in a secure directory outside of the web root to prevent direct access.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    $targetDir = 'uploads/';
    $targetFile = $targetDir . basename($_FILES['file']['name']);
    
    // Validate file type
    $fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
    if($fileType != 'jpg' && $fileType != 'png'){
        echo 'Only JPG and PNG files are allowed.';
    } else {
        // Move the file to the uploads directory
        move_uploaded_file($_FILES['file']['tmp_name'], $targetFile);
        echo 'File uploaded successfully.';
    }
} else {
    echo 'Error uploading file.';
}
?>