0

I take a web address as an input from the user using a form element in HTML:

<form action="parse.php" method="post">
        Web address :
        <input type="text" name="addr">
        <input type=submit value="Go">
</form>

The problem is that the user can enter a url in the any of the following formats:

google.com
www.google.com
http://www.google.com

No matter what the user enters, I want the url to be of form http://www.google.com.

What's the best way to implement this in php, other than checking for all possibilities?

seaotternerd
  • 6,298
  • 2
  • 47
  • 58

2 Answers2

0

You have to either check all possibilities or use a regular expression to test its validity.

Alternatively you can verify the input using client side Javascript.

Finally, you can check the URL input for protocol, if not present default to "http://" and prepend it to the URL string.

Wren
  • 633
  • 5
  • 13
0

Something along these lines should work with a little bit of tweaking:

$address = htmlspecialchars($_POST['addr']);

if (substr($address, -3, 3) != 'com') {
    $address = $address.".com";
}
if (substr($address, 0, 7) != 'http://') {
    $address = "http://".$address;
}

echo $address;

First, the input is taken from the form, and santizied. Then, substr checks the last 3 characters of the input to see if 'com' is present. If it isn't, it will append '.com' to the end. Same for http://

Hope this helps!

  • This won't work with any gTLD, '.org', '.net' etc... And would also prepend "http://" to the start of a URL which starts with "https://" – Wren Nov 23 '13 at 11:53