What are some best practices for handling directory and file paths in PHP, especially when using functions like pathinfo()?

When working with directory and file paths in PHP, it's important to handle them carefully to avoid issues with file system operations. One common function used for parsing paths is pathinfo(), which can help extract information like the directory name, filename, and extension. To ensure compatibility across different operating systems, it's recommended to use the DIRECTORY_SEPARATOR constant when constructing paths.

// Example of handling directory and file paths using pathinfo() and DIRECTORY_SEPARATOR

// Define the path to the file
$file_path = 'path/to/file/example.txt';

// Use pathinfo() to extract information about the file path
$path_info = pathinfo($file_path);

// Construct a new path using DIRECTORY_SEPARATOR for compatibility
$new_path = $path_info['dirname'] . DIRECTORY_SEPARATOR . 'new_filename.' . $path_info['extension'];

echo $new_path; // Output: path/to/file/new_filename.txt