How can PHP be used to validate and sanitize URLs entered by users in a guestbook or similar form?

To validate and sanitize URLs entered by users in a guestbook or form, you can use PHP's filter_var function with the FILTER_VALIDATE_URL filter to validate the URL format. Additionally, you can use the filter_var function with the FILTER_SANITIZE_URL filter to sanitize the URL by removing any potentially harmful characters.

// Validate and sanitize URL input from user
$url = $_POST['url'];

if (filter_var($url, FILTER_VALIDATE_URL)) {
    $sanitized_url = filter_var($url, FILTER_SANITIZE_URL);
    // Process the sanitized URL
} else {
    // Handle invalid URL input
}