Are there any best practices for handling directory navigation in PHP to prevent security vulnerabilities?

Directory traversal attacks can occur when user input is not properly sanitized, allowing malicious users to navigate to directories outside of the intended scope. To prevent this, it is important to validate and sanitize user input before using it to navigate directories in PHP. One way to do this is by using the realpath() function to get the full path of a directory and then compare it with a base directory to ensure it falls within the expected scope.

$userInput = $_GET['directory'];

$baseDirectory = '/path/to/base/directory/';

$fullPath = realpath($baseDirectory . $userInput);

if (strpos($fullPath, $baseDirectory) !== 0) {
    // Invalid directory path
    die('Invalid directory path');
}

// Use $fullPath to navigate directories safely