What are the best practices for handling file operations like fopen in PHP scripts to ensure compatibility across different servers?

When handling file operations like fopen in PHP scripts, it's important to consider the differences in server configurations that may affect the file paths. To ensure compatibility across different servers, it's recommended to use the `DIRECTORY_SEPARATOR` constant to build file paths dynamically and to check for the existence of directories before attempting to create files.

<?php

// Define the file path using DIRECTORY_SEPARATOR
$filePath = 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'file.txt';

// Check if the directory exists, create it if it doesn't
$directory = dirname($filePath);
if (!is_dir($directory)) {
    mkdir($directory, 0755, true);
}

// Open the file for writing
$file = fopen($filePath, 'w');

// Write content to the file
fwrite($file, 'Hello, world!');

// Close the file
fclose($file);

?>