What are the best practices for handling file paths and directory operations in PHP scripts?

When working with file paths and directory operations in PHP scripts, it is important to use built-in functions such as realpath() to ensure that paths are resolved correctly and to avoid issues with relative paths. It is also recommended to use DIRECTORY_SEPARATOR constant when constructing paths to make the code platform-independent. Additionally, always check for file existence before performing any operations to avoid errors.

// Example of using realpath() and DIRECTORY_SEPARATOR for handling file paths
$path = '/path/to/file.txt';
$realPath = realpath($path);

if ($realPath !== false) {
    $newPath = $realPath . DIRECTORY_SEPARATOR . 'newfile.txt';
    // Perform operations on the new path
} else {
    echo 'File does not exist';
}