0

so i have this website where people can submit url's for certain items, but I dont know how i can validate that a url was submitted not just some crap!.

Atm i have this piece of code:

if(filter_var('http://www.example.com/test.html', FILTER_VALIDATE_URL)) {
    echo 'this is URL';
} else {
    echo 'this is no url!';
}

But this piece of code is easy to bypass since it only checks for "http" in the string, And users will submit "host" separately so i need to check if $host is a valid host.

Thx in advance! you guys rock!

Annika Backstrom
  • 13,937
  • 6
  • 46
  • 52
Zenel Shabani
  • 95
  • 1
  • 1
  • 10
  • 1
    possible duplicate of [PHP validation/regex for URL](http://stackoverflow.com/questions/206059/php-validation-regex-for-url) – Tobias Golbs Sep 11 '13 at 13:42
  • `since it only checks for "http" in the string` -- really? It validates according to http://www.faqs.org/rfcs/rfc2396 – Amal Murali Sep 11 '13 at 13:45
  • 1
    The only way to check if a URL is valid is to actually call it and see what you get. You would want to do the same for, for instance, email addresses but that's arguably a little bit harder. – Halcyon Sep 11 '13 at 13:48

2 Answers2

0

How about sending it an HTTP request?

function isValid($url) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_NOBODY, true); //make it a HEAD request
    curl_exec($curl);

    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    return $statusCode == 200;
}

var_dump(isValid('http://www.google.co.uk')); // bool(true)
var_dump(isValid('some invalid URL')); // bool(false)
George Brighton
  • 5,131
  • 9
  • 27
  • 36
0

Here is an example that solves your problem :

<?php
$url = "http://www.example.com/test.html";
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
  echo "URL is valid";
}
else {
  echo "URL is invalid";
}
?>
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44