Are there any best practices for handling file uploads and setting permissions in PHP to avoid errors related to directory access restrictions?

When handling file uploads in PHP, it's important to ensure that the directory where the files are being saved has the correct permissions set to avoid access restrictions. One way to do this is by setting the directory permissions to allow read, write, and execute access for the web server user. Additionally, you can use PHP's `chmod()` function to set the correct permissions for the uploaded files.

// Set the directory where files will be uploaded
$uploadDir = '/path/to/upload/directory/';

// Create the directory if it doesn't exist
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Set the correct permissions for the directory
chmod($uploadDir, 0777);

// Handle file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tempFile = $_FILES['file']['tmp_name'];
    $targetFile = $uploadDir . $_FILES['file']['name'];
    
    // Move the uploaded file to the target directory
    move_uploaded_file($tempFile, $targetFile);
    
    // Set the correct permissions for the uploaded file
    chmod($targetFile, 0644);
}