Are there any security concerns to consider when passing PHP variables to JavaScript functions?

When passing PHP variables to JavaScript functions, it is important to be cautious of potential security vulnerabilities such as Cross-Site Scripting (XSS) attacks. To mitigate this risk, it is recommended to properly sanitize and escape the PHP variables before passing them to JavaScript functions. This can be achieved by using functions like json_encode() or htmlspecialchars() to ensure that the data is safe to use in a JavaScript context.

<?php
// Example PHP variable
$phpVariable = "<script>alert('XSS attack!');</script>";

// Sanitize and escape the PHP variable before passing it to a JavaScript function
$escapedVariable = htmlspecialchars($phpVariable, ENT_QUOTES, 'UTF-8');

// Pass the escaped variable to a JavaScript function
echo "<script>myFunction('$escapedVariable');</script>";
?>