What are the best practices for handling user input, such as emails and URLs, in PHP applications to avoid errors?

When handling user input such as emails and URLs in PHP applications, it is important to validate and sanitize the input to prevent errors and potential security vulnerabilities. One way to do this is by using built-in PHP functions like filter_var() with the FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_URL filters to validate emails and URLs respectively. Additionally, using regular expressions can help ensure that the input matches the expected format.

// Validate email input
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Email is valid
} else {
    // Invalid email format
}

// Validate URL input
$url = $_POST['url'];
if (filter_var($url, FILTER_VALIDATE_URL)) {
    // URL is valid
} else {
    // Invalid URL format
}