What are some best practices for handling file transfers in PHP to ensure that the process is efficient and secure?

When handling file transfers in PHP, it is essential to ensure that the process is both efficient and secure. To achieve this, it is recommended to use secure file upload methods, validate file types and sizes, sanitize file names to prevent directory traversal attacks, and store uploaded files outside the web root directory to prevent direct access.

// Example of handling file upload in PHP

// Check if file is uploaded
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
    if(!in_array($file['type'], $allowed_types)) {
        die('Invalid file type.');
    }

    // Validate file size
    if($file['size'] > 1048576) {
        die('File is too large.');
    }

    // Sanitize file name
    $file_name = basename($file['name']);
    $file_path = '/path/to/upload/directory/' . $file_name;

    // Move uploaded file to secure directory
    if(move_uploaded_file($file['tmp_name'], $file_path)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
}