When should PHP paths be sanitized using htmlspecialchars?

PHP paths should be sanitized using htmlspecialchars when displaying them on a webpage to prevent potential Cross-Site Scripting (XSS) attacks. By using htmlspecialchars, special characters in the path will be converted to their HTML entities, ensuring that the path is displayed as plain text and cannot be interpreted as HTML or JavaScript by the browser.

$path = "/path/to/file.php";
$sanitized_path = htmlspecialchars($path);
echo $sanitized_path;