W3docs

How to add http:// if it doesn't exist in the URL

You can use the following code snippet to add "http://" to the beginning of a URL if it doesn't already exist:

You can use the following code snippet to add "http://" to the beginning of a URL if it doesn't already exist:

Example of how to add http if it doesn't exist in the URL in PHP

<?php

// Define the URL
$url = "www.example.com";

// Check if the URL does not have an http or https protocol
if (!preg_match("~^https?://~i", $url)) {
    // Add the HTTP protocol to the URL
    $url = "http://" . $url;
}

// Output the URL
echo "The URL is: " . $url;

?>

This uses the preg_match function to check if the URL starts with http:// or https://. If it doesn't, it prepends http:// to the beginning of the URL. Note that this simple approach does not handle protocol-relative URLs (e.g., //example.com). For production environments, consider using parse_url() or filter_var() for more robust URL validation.