URL Validation

$url = 'http://example.com';
$validation = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);

if ( $validation ) $output = 'proper URL';
else $output = 'wrong URL';

echo $output;


  1. User Avatar
    Permalink to comment#

    $output = ‘proper UL’;
    I think there is a typo in that line.

  2. User Avatar
    Emilio CS
    Permalink to comment#

    I think it needs improvements. The code will pass the url “http://www.example” as valid url.

  3. User Avatar
    Aneek Mukhopadhyay
    Permalink to comment#

    filter_var is good one but I still have faith in good old preg_match() and the regular expressions.


  4. User Avatar
    Heinrich Reimer
    Permalink to comment#

    My regex for URL validation (validates GET variables and “#” after URLs too):

    preg_match("/^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})(\/([\da-z\.-]+))*\/?(([\w\.-]+)\.([\da-z]{2,6}))?((\#[\w\.-]+)|(\?([\da-z]+(=[\da-z]+)?)(&([\da-z]+(=[\da-z]+)?))*))?/i", $url);

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.