What are the best practices for handling file permissions and directory access when writing files in PHP, particularly when using libraries like GD-Lib for image manipulation?

When writing files in PHP, it is important to ensure that proper file permissions are set to prevent unauthorized access or modifications. This is especially crucial when using libraries like GD-Lib for image manipulation, as it involves creating and saving files on the server. To handle file permissions and directory access securely, it is recommended to set the correct permissions for the directories where files will be saved and to use PHP's `chmod()` function to set appropriate permissions for the created files.

// Set the directory where the file will be saved
$directory = 'uploads/';

// Check if the directory exists, if not create it
if (!file_exists($directory)) {
    mkdir($directory, 0777, true);
}

// Set the file path
$file_path = $directory . 'image.jpg';

// Perform image manipulation with GD-Lib

// Save the manipulated image to the file path
imagejpeg($image_resource, $file_path);

// Set appropriate permissions for the file
chmod($file_path, 0644);