What are some best practices for ensuring that file creation and writing functions work properly in PHP on a web server?

When creating and writing files in PHP on a web server, it is important to ensure that the correct permissions are set for the directory where the files will be created. This includes making sure that the directory is writable by the web server user. Additionally, it is good practice to check for errors when creating or writing files to handle any potential issues that may arise.

// Check if the directory is writable
if (!is_writable('/path/to/directory')) {
    die('Directory is not writable');
}

// Create a new file and write content to it
$file = fopen('/path/to/directory/newfile.txt', 'w');
if ($file) {
    fwrite($file, 'Hello, world!');
    fclose($file);
    echo 'File created and written successfully';
} else {
    echo 'Error creating file';
}