Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Created March 3, 2020 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finalwebsites/529e27997a536723a28afa731de654ff to your computer and use it in GitHub Desktop.
Save finalwebsites/529e27997a536723a28afa731de654ff to your computer and use it in GitHub Desktop.
Use this function to fix the missing protocol part from an URL
<?php
function check_url($url) {
if (substr($url, 0, 4) != 'http') {
$url = 'http://'.$url;
}
$response = get_headers($url);
if ($response[0] == 'HTTP/1.1 200 OK') {
return $url;
} elseif (in_array(substr($response[0], 9, 3), array(302, 301))) {
foreach ($response as $r) {
if (substr($r, 0, 8) == 'Location') {
return str_replace('Location: ', '', $r);
break;
}
}
} elseif (substr($response[0], 9, 3) >= 400) {
return '';
}
}
echo check_url('www.finalwebsites.com');
@finalwebsites
Copy link
Author

I have customers or user which enter a website address without the protocol (http:// or https://).
Sure you can use some URL validation, but this function can fix it too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment