What are some best practices for handling user-generated content with URLs in PHP applications to prevent vulnerabilities?

User-generated content with URLs in PHP applications can pose security risks such as cross-site scripting (XSS) attacks or directory traversal vulnerabilities. To prevent these vulnerabilities, it is important to properly sanitize and validate user input before using it to construct URLs. This can be done by using functions like filter_var() to validate URLs and htmlentities() to escape special characters.

// Sanitize and validate user-generated URL input
$user_input_url = filter_var($_POST['url'], FILTER_VALIDATE_URL);

// Escape special characters in the URL
$safe_url = htmlentities($user_input_url);