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:

<?php

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

// Check if the URL does not have a protocol
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
    // Add the HTTP protocol to the URL
    $url = "http://" . $url;
}

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

?>

Watch a course Learn object oriented PHP

This uses the preg_match function to check if the URL starts with "http://" or "https://", and if it doesn't, it prepends "http://" to the beginning of the URL.