What are some recommended approaches for handling user-generated links in PHP to maintain forum integrity?

User-generated links in forums can pose a security risk if not properly handled. To maintain forum integrity, it is recommended to sanitize and validate user-generated links before displaying them. One approach is to use PHP's filter_var() function with the FILTER_VALIDATE_URL filter to ensure the link is a valid URL. Additionally, you can use htmlspecialchars() to escape any HTML characters in the link to prevent XSS attacks.

// Sanitize and validate user-generated link
$userLink = filter_var($_POST['user_link'], FILTER_VALIDATE_URL);

// Escape HTML characters in the link
$escapedLink = htmlspecialchars($userLink);

// Display the sanitized link
echo "<a href='$escapedLink'>User Link</a>";