Are there any security considerations to keep in mind when passing variables between PHP and JavaScript?

When passing variables between PHP and JavaScript, it is important to sanitize and validate the data to prevent any security vulnerabilities such as cross-site scripting (XSS) attacks. One way to do this is by using functions like htmlspecialchars() in PHP to encode the data before passing it to JavaScript.

<?php
// Sanitize and encode the variable before passing it to JavaScript
$variable = "<script>alert('XSS attack!');</script>";
$encoded_variable = htmlspecialchars($variable, ENT_QUOTES, 'UTF-8');
?>

<script>
// Use the encoded variable in JavaScript
var jsVariable = "<?php echo $encoded_variable; ?>";
console.log(jsVariable);
</script>