What best practices should be followed when handling directory navigation in PHP scripts like the one provided?

When handling directory navigation in PHP scripts, it is important to sanitize user input to prevent directory traversal attacks. One way to do this is by using the realpath() function to get the absolute path of the directory and ensure that it is within the allowed directory structure. Additionally, it is recommended to use the DIRECTORY_SEPARATOR constant to build paths in a platform-independent way.

// Sanitize user input for directory navigation
$directory = isset($_GET['dir']) ? $_GET['dir'] : '';
$baseDir = '/path/to/allowed/directory/';

// Get the absolute path of the directory
$absoluteDir = realpath($baseDir . DIRECTORY_SEPARATOR . $directory);

// Check if the absolute path is within the allowed directory structure
if (strpos($absoluteDir, $baseDir) === 0) {
    // Directory navigation is safe to proceed
    // Your code here
} else {
    // Invalid directory path
    echo 'Invalid directory path';
}