How can file permissions be set for a directory in PHP to allow both uploading and viewing of files?

When setting file permissions for a directory in PHP to allow both uploading and viewing of files, you need to ensure that the directory has the correct permissions for both actions. This can be achieved by setting the directory permissions to allow the web server to write to it for file uploads (e.g., 755 or 777) and also ensuring that the directory is readable by the web server for file viewing.

// Set directory permissions for uploading and viewing files
$directory = 'uploads/';

// Set permissions for uploading files
if (!file_exists($directory)) {
    mkdir($directory, 0777, true);
}

// Set permissions for viewing files
chmod($directory, 0755);