How can PHP developers ensure that user input, such as URLs, is properly validated and sanitized to prevent vulnerabilities in their code?

PHP developers can ensure that user input, such as URLs, is properly validated and sanitized by using PHP's filter_var() function with the FILTER_VALIDATE_URL filter. This function will validate the URL format and ensure that it is safe to use in the code. Additionally, developers should also escape any user input that is being outputted to prevent cross-site scripting (XSS) attacks.

// Validate and sanitize user input URL
$user_input_url = $_POST['url'];
if (filter_var($user_input_url, FILTER_VALIDATE_URL)) {
    $safe_url = filter_var($user_input_url, FILTER_SANITIZE_URL);
    // Use $safe_url in your code
} else {
    // Handle invalid URL input
}