What are some best practices for retrieving and handling script paths in PHP to ensure compatibility and security across different environments?

When retrieving and handling script paths in PHP, it is important to use built-in functions like realpath() to ensure the path is resolved correctly and securely across different environments. Additionally, sanitizing user input and validating paths can help prevent directory traversal attacks.

// Example of retrieving and handling script paths securely
$path = '/path/to/file.php';
$realPath = realpath($path);

if ($realPath !== false && strpos($realPath, '/path/to/') === 0) {
    // Path is valid and within the expected directory
    echo "Valid path: " . $realPath;
} else {
    // Invalid path
    echo "Invalid path";
}