Validation of local urls

Published on and tagged with cakephp  validation

While working on NoseRub I noticed (once again) that the validation of urls in the form of “http://somename.localhost” fails when using CakePHP’s built-in url validation rule.

To make such urls pass the validation we have to write a custom validation rule. As PHP (>= 5.2.0) already provides a filter for urls we can use this filter in our validation rule. And so the code in our model looks like:

public $validate = array('url' => array('rule' => array('validateUrl')));

public function validateUrl($data) {
    return (filter_var($data['url'], FILTER_VALIDATE_URL)) ? true : false;

I hope this workaround is useful for some of you.

PS: If you are a German-speaking baker, a new blog called cakery (started by Siegfried Hirsch, the admin of the German CakePHP Google Group) could be interesting for you.

4 comments baked

  • Mark Story

    hey daniel, just a heads up, many of the links on are broken.

    all aren’t working for me.

  • Siegfried

    HeyDaniel, thanks a lot for linking. My openID questions are not forgotten but a little bit postponed. Will contact you again.

  • David Thalmann

    Never heard of the function filter_var() function, thanx for your post! But just saw this:

    “It seems that all FILTER_VALIDATE_URL is doing is calling parse_url(), which makes it effectively useless since parse_url() only fails on really malformed urls.

    $url = 'http://...';
    var_dump(filter_var($url, FILTER_VALIDATE_URL));

    Will display: string(10) “http://…”

    None of the flags help either, so you’re better off with regular expressions to validate a url.” From

  • cakebaker

    @all: Thanks for your comments!

    @Mark: It seems like Dirk already fixed the links, at least now they work ;-) Only the NoseRub blog is currently offline as it got “hacked” yesterday… It will be back soon. Anyway, thanks for the heads up!

    @Siegfried: No problem, it is good to have a German CakePHP blog :)

    @David: Thanks for this hint. I think the “problem” is that something like http://. is in fact a valid url. So in practice you probably have to perform some additional checks to ensure a stricter url format…

© daniel hofstetter. Licensed under a Creative Commons License