What are some best practices for handling file uploads in PHP, and where can one find resources to learn more about this topic?

When handling file uploads in PHP, it is important to validate the file type, size, and name to prevent security vulnerabilities. Additionally, always store uploaded files in a secure directory outside of the web root to prevent direct access. Finally, consider using libraries like Symfony's HttpFoundation component or Laravel's Storage facade for more advanced file handling capabilities.

<?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 = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif"){
        echo "Only JPG, JPEG, PNG & GIF files are allowed.";
        exit;
    }

    // Validate file size
    if($_FILES["file"]["size"] > 500000){
        echo "File is too large.";
        exit;
    }

    // Move uploaded file to secure directory
    if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)){
        echo "File uploaded successfully.";
    } else {
        echo "Error uploading file.";
    }
} else {
    echo "Error uploading file.";
}
?>