What are some best practices to ensure successful file uploads in PHP?

To ensure successful file uploads in PHP, it is important to set the correct file upload settings in php.ini, validate the file type and size on the server-side, and move the uploaded file to a secure directory on the server.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    // Validate file type
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    if(!in_array($file_extension, $allowed_types)){
        echo 'Invalid file type. Allowed types: jpg, jpeg, png, gif';
        exit;
    }

    // Validate file size (max 5MB)
    if($_FILES['file']['size'] > 5 * 1024 * 1024){
        echo 'File is too large. Maximum size allowed is 5MB';
        exit;
    }

    // Move uploaded file to secure directory
    $upload_dir = 'uploads/';
    $upload_file = $upload_dir . basename($_FILES['file']['name']);
    if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)){
        echo 'File uploaded successfully';
    } else {
        echo 'Error uploading file';
    }
} else {
    echo 'Error uploading file';
}
?>