What are the best practices for handling file uploads in PHP when using Phonegap for a mobile application?

When handling file uploads in PHP for a mobile application using Phonegap, it is important to ensure that the file uploads are secure and properly handled. One best practice is to validate the file type and size before processing the upload. Additionally, it is recommended to store the 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){
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];
    
    // Validate file type
    $file_ext = strtolower(end(explode('.', $file_name)));
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
    
    if(in_array($file_ext, $allowed_extensions)){
        // Move the uploaded file to a secure directory
        $upload_path = 'uploads/' . $file_name;
        move_uploaded_file($file_tmp, $upload_path);
        
        echo 'File uploaded successfully.';
    } else {
        echo 'Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.';
    }
} else {
    echo 'Error uploading file.';
}
?>