Are there any best practices for ensuring that URLs entered in a form always have the http:// or https:// prefix in PHP?

When users enter URLs in a form, they may forget to include the http:// or https:// prefix, which can lead to broken links. To ensure that URLs always have the correct prefix, we can use PHP to check if the prefix is present and add it if necessary before saving the URL.

// Check if the URL entered in the form has the http:// or https:// prefix
$url = $_POST['url'];

if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
    $url = 'http://' . $url; // Add http:// prefix if not present
}

// Now $url contains the URL with the correct prefix