The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "SVG" Oct 14 - 6:30 PM Eastern
Get a free trial // Grow your CSS skills // Land your dream job

URL Validation

Last updated on:
$url = '';
$validation = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);

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

echo $output;


  1. Will
    Permalink to comment#

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

  2. Emilio CS
    Permalink to comment#

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

  3. 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. 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

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed