What best practices should be followed when handling file transfers in PHP?

When handling file transfers in PHP, it is important to follow best practices to ensure security and reliability. This includes validating file types, setting appropriate file permissions, using secure file paths, and handling errors gracefully.

// Example code for handling file uploads in PHP
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);
    
    // Validate file type
    $fileType = pathinfo($uploadFile, PATHINFO_EXTENSION);
    if ($fileType != 'jpg' && $fileType != 'png') {
        echo 'Invalid file type. Only JPG and PNG files are allowed.';
        exit;
    }
    
    // Move the uploaded file to the upload directory
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Error uploading file: ' . $_FILES['file']['error'];
}