What are the best practices for handling URLs retrieved from a database in PHP for use in JavaScript?

When handling URLs retrieved from a database in PHP for use in JavaScript, it's important to properly escape the URLs to prevent any security vulnerabilities like XSS attacks. One way to do this is by using the htmlspecialchars() function in PHP to encode special characters in the URL before outputting it in JavaScript.

<?php
// Retrieve URL from database
$url = "http://example.com/page?id=1";

// Escape the URL for use in JavaScript
$escaped_url = htmlspecialchars($url, ENT_QUOTES);

// Output the escaped URL in JavaScript
echo "<script>var url = '$escaped_url';</script>";
?>