What are some best practices for ensuring successful file uploads in PHP?

When handling file uploads in PHP, it is important to ensure that the necessary server configurations are set correctly, such as increasing the upload_max_filesize and post_max_size values in php.ini. Additionally, validating the file type and size on the server-side can help prevent malicious uploads. Finally, using move_uploaded_file() function to move the uploaded file to a secure directory is a best practice.

<?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"]);
    
    // Validate file type
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $file_extension = pathinfo($target_file, PATHINFO_EXTENSION);
    if(!in_array($file_extension, $allowed_types)){
        echo "Invalid file type. Allowed types: jpg, jpeg, png, gif";
    } else {
        // Move the uploaded file to a secure directory
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
            echo "File uploaded successfully.";
        } else {
            echo "Error uploading file.";
        }
    }
} else {
    echo "Error uploading file.";
}
?>