What best practices should be followed when working with file uploads in PHP?

When working with file uploads in PHP, it is important to follow best practices to ensure the security and integrity of your application. This includes validating file types, checking file sizes, and storing files in a secure location on the server. Additionally, it is recommended to use functions like move_uploaded_file() to handle file uploads securely.

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

    // Check file size
    if ($_FILES["file"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
    } else {
        // Check file type
        $file_type = pathinfo($target_file,PATHINFO_EXTENSION);
        if($file_type != "jpg" && $file_type != "png" && $file_type != "jpeg"
            && $file_type != "gif" ) {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        } else {
            // Store file in uploads folder
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
                echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    }
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>