What are the best practices for handling file uploads in PHP to avoid permission-related errors like the one mentioned in the forum thread?

When handling file uploads in PHP, it is essential to ensure that the destination directory has the appropriate permissions set to allow the web server to write to it. This can be done by changing the ownership of the directory to the web server user or by granting write permissions to the directory. Additionally, it is good practice to validate the file type and size before moving the uploaded file to the destination directory to prevent security vulnerabilities.

// Ensure the destination directory has the correct permissions
$uploadDirectory = '/path/to/upload/directory/';
if (!is_dir($uploadDirectory)) {
    mkdir($uploadDirectory, 0755, true);
}

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 1048576; // 1MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadDirectory . $_FILES['file']['name']);
    echo 'File uploaded successfully!';
} else {
    echo 'Invalid file type or size.';
}