Part of the EllisLab Network
   
1 of 2
1
Valid url check in form validation
Posted: 10 April 2009 10:42 AM   [ Ignore ]  
Lab Assistant
RankRank
Total Posts:  200
Joined  07-31-2008

Here’s a little something you can add into the Form_validation.php to check urls. One just checks the syntax. The other actually checks to see if the website exists. Feel free to improve the regex as I’m by no means claiming to be an expert! smile

// --------------------------------------------------------------------
    
    /**
     * Validate URL
     *
     * @access    public
     * @param    string
     * @return    string
     */
    
function valid_url($url)
    
{
        $pattern 
"/^((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?/";
        if (!
preg_match($pattern$url))
        
{
            
return FALSE;
        
}

        
return TRUE;
    
}
    
    
// --------------------------------------------------------------------
    
    /**
     * Real URL
     *
     * @access    public
     * @param    string
     * @return    string
     */
    
function real_url($url)
    
{
        
return @fsockopen("$url"80$errno$errstr30);
    


Don’t forget to explain to visitors that they don’t need to append “http://” to the url when you’re validating against real_url()!!!

 Signature 

Spam Helper | Html Helper | GPoll Library | IMAP Library

Profile
 
 
Posted: 10 April 2009 12:42 PM   [ Ignore ]   [ # 1 ]  
Lab Assistant
RankRank
Total Posts:  115
Joined  10-19-2008

Hi Iverson,

Great contribution, I have always been a little surprised that this function was not included as a built-in rule. This will be useful on a current project, so thank you.

You included a match for the port specification… nice!

I did find one bug - this regex will match “www.domain.co.u-k”.

There’s a great online regex tester [URL=http://ryanswanson.com/regexp/#start]here[/url]. The site also has some great examples of regexs, including some good ones for URLs (neither of which are perfect):

/(((http|ftp|https):\/\/){1}([a-zA-Z0-9_-]+)(\.[a-zA-Z0-9_-]+)+([\S,:\/\.\?=a-zA-Z0-9_-]+))/igs
/^((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))?(:[\d]{1,5})?+([a-zA-Z0-9\/\_\?\.\,\&]+)?/ 
Profile
 
 
Posted: 10 April 2009 01:06 PM   [ Ignore ]   [ # 2 ]  
Lab Assistant
RankRank
Total Posts:  200
Joined  07-31-2008

Yeah me too. Hopefully the next version will come with it. If it does I’m sure it’ll be better than mine. I’ve updated the code with the better regex.

 Signature 

Spam Helper | Html Helper | GPoll Library | IMAP Library

Profile
 
 
Posted: 19 August 2009 06:38 AM   [ Ignore ]   [ # 3 ]  
Summer Student
Total Posts:  3
Joined  03-10-2009

Just a quick heads up. “http://en.wikipedia.org” is not considered a valid URL according to the regex tester mentioned by Mike Ryan.

Profile
 
 
Posted: 31 October 2009 11:12 AM   [ Ignore ]   [ # 4 ]  
Research Assistant
RankRankRank
Total Posts:  320
Joined  11-06-2008
Bruno De Barros @ Terra Duo - 19 August 2009 10:38 AM

Just a quick heads up. “http://en.wikipedia.org” is not considered a valid URL according to the regex tester mentioned by Mike Ryan.

Hello everyone

I wanted to ask, how do I validate url,

so:
http(s)://example.com
http(s)://*.example.com
http(s)://example.com/*
http(s)://www.example.com/*
http(s)://*.example.com/*

As a result I just need to get true/false..
can someone help me?

thanks!

Profile
 
 
Posted: 31 October 2009 04:02 PM   [ Ignore ]   [ # 5 ]  
Grad Student
Rank
Total Posts:  93
Joined  12-22-2006

I get the following error:

A PHP Error was encountered

Severity: Warning

Message: preg_match() [function.preg-match]: Unknown modifier ‘|’

Filename: libraries/MY_Form_validation.php

Line Number: 20

Profile
 
 
Posted: 01 November 2009 03:29 AM   [ Ignore ]   [ # 6 ]  
Research Assistant
RankRankRank
Total Posts:  320
Joined  11-06-2008
Muser - 31 October 2009 08:02 PM

I get the following error:

A PHP Error was encountered

Severity: Warning

Message: preg_match() [function.preg-match]: Unknown modifier ‘|’

Filename: libraries/MY_Form_validation.php

Line Number: 20

can you paste exact function/rule?

Profile
 
 
Posted: 28 January 2010 01:11 PM   [ Ignore ]   [ # 7 ]  
Grad Student
Rank
Total Posts:  86
Joined  10-31-2009
Mike Ryan - 10 April 2009 04:42 PM

Hi Iverson,

Great contribution, I have always been a little surprised that this function was not included as a built-in rule.

Look at line 7 in system/language/english/form_validation_lang.php :

$lang['valid_url']             "The %s field must contain a valid URL."

And yet, you’re right, I can’t see a valid_url() function in the form_validation library. Maybe I’m missing something, or maybe someone was planning to create a valid_url() validation function and, err, forgot?  cool smirk

Profile
 
 
Posted: 28 January 2010 01:36 PM   [ Ignore ]   [ # 8 ]  
Grad Student
Rank
Total Posts:  86
Joined  10-31-2009

Since I can’t find it built in to the form_validation library, I’ve created a MY_form_validation library with a valid_url() function in it:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
MY_form_validation extends CI_form_validation {

    
function valid_url($str){

           $pattern 
"/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
            if (!
preg_match($pattern$str))
            
{
                
return FALSE;
            
}

            
return TRUE;
    
}


Which I call in my validation rules like this:

$this->load->helper('url');
$this->form_validation->set_rules('author_url''Website''trim|prep_url|valid_url|xss_clean'); 

NB the regex in the valid_url() function requires an http:// or https:// or ftp:// prefix. I’ve added prep_url to the validation rule to add http:// if it is required. That’s why I’ve loaded the URL helper first.

As expected, when validation fails on the author_url field, CodeIgniter displays this message:

The Website field must contain a valid URL

Straight out of the form_validation_lang.php file. Weird that it never made it into the form_validation library.

Profile
 
 
Posted: 15 July 2010 04:41 AM   [ Ignore ]   [ # 9 ]  
Summer Student
Total Posts:  2
Joined  03-29-2010

Just as Aidehua i made a MY_ library.
Only i used the php built in function filter_var

so it gets more clean, and you dont need to prep_url.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
MY_form_validation extends CI_form_validation {

    
function valid_url($str){
            
if(filter_var($strFILTER_VALIDATE_URL)){
                
return TRUE;
            
}
            else{
                
return FALSE;
            
}
        }


EDIT:

Also could be:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
MY_form_validation extends CI_form_validation {

    
function valid_url($str){
            
return filter_var($strFILTER_VALIDATE_URL)
            
}
 Signature 

“Matter flows from place to place and momentarily comes together to be you. Some people find that thought disturbing.
I find the reality thrilling”

~Clinton Richard Dawkins

Profile
 
 
Posted: 15 July 2010 05:55 AM   [ Ignore ]   [ # 10 ]  
Sr. Research Associate
Avatar
RankRankRankRankRank
Total Posts:  3862
Joined  11-04-2008

Not a good idea.

First of all, filter_var() is PHP 5.2.0+, which is not always available. And second, it does a very lousy job in validating a URL. Internally, it only checks if a parse_url() is possible, for with the PHP documentation states that it should not be used for URL validation.

 Signature 

WanWizard.eu | Modular CI, an HMVC solution | DataMapper ORM

Profile
 
 
   
1 of 2
1