Home > codeigniter, dev, open source, php, Tech > URL Validation in CodeIgniter

URL Validation in CodeIgniter

CodeIgniter comes with a lot of great validators and libraries out of the box, but once place I’ve found it to be lacking is with URL validation. It has nice support for validating email addresses but almost nothing for URL checks. The only one that it provides is called prep_url which does nothing more then prepend “http://” to input text.

I wanted to be able to validate that the URL was properly formatted, things such as:

  • scheme
  • host
  • port
  • path
  • etc

However, there was nothing out of the box that handled this. I also wanted to validate that if the URL was properly formatted that the domain actually existed. So I built this out as well. To handle this you simple have to add a new library under application/libraries called MY_validation.php. This will allow you to extend the built-in validation library and add additional validators to it.

Then in your code, you can simply add additional validators like:

$rules['URL']  = 'required|trim|max_length[256]|xss_clean|prep_url|valid_url_format|url_exists|callback_duplicate_URL_check';

The two new validators are valid_url_format which checks for a properly formatted URL and url_exists which checks for a valid server. You should prefix the two with prep_url so that if they don’t enter a scheme the other validators won’t fail. The final validator, callback_duplicate_url_check is a custom validator for this controller that ensures the URL isn’t already loaded into the system.

So simply create ci/system/application/libraries/MY_validation.php and paste the following contents into it. Then be sure to load the validation library in your controller/method ($this->load->library(‘validation’);) and you should be good to go!

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

/**
 * Additional validations for URL testing.
 *
 * @package      Module Creator
 * @subpackage	ThirdParty
 * @category	Libraries
 * @author	Brian Antonelli <brian.antonelli@autotrader.com>
 * @created	11/19/2010
 */

class MY_validation extends CI_validation{
    
    function MY_validation(){
        parent::CI_validation();
    }                                
                        
    /**
	 * Validate URL format
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */	
    function valid_url_format($str){
        $pattern = "|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i";
        if (!preg_match($pattern, $str)){
            $this->set_message('valid_url_format', 'The URL you entered is not correctly formatted.');
            return FALSE;
        }

        return TRUE;
    }       

	// --------------------------------------------------------------------
    

    /**
	 * Validates that a URL is accessible. Also takes ports into consideration. 
	 * Note: If you see "php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known" 
	 *          then you are having DNS resolution issues and need to fix Apache
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */	
    function url_exists($url){                                   
        $url_data = parse_url($url); // scheme, host, port, path, query
        if(!fsockopen($url_data['host'], isset($url_data['port']) ? $url_data['port'] : 80)){
            $this->set_message('url_exists', 'The URL you entered is not accessible.');
            return FALSE;
        }               
        
        return TRUE;
    }  
}

  1. alberto
    March 13, 2011 at 1:43 am

    In CI 2.0 teh validation class was removed (deprecated), now you should use instead Form_validation

  2. November 19, 2014 at 8:54 pm

    Hello, all is going nicely here and ofcourse every one
    is sharing data, that’s actually good, keep up writing.

  3. November 27, 2014 at 2:00 am

    What’s up, yes this article is really nice and I have learned lot of things from it about blogging.
    thanks.

  1. No trackbacks yet.

Leave a comment