1

Using Querystrings in CodeIgniter

Posted (Updated ) in PHP

By default, CodeIgniter only allows segment-based URLs, however it is also possible with a little fiddling to use querystrings.

http://domain.com/this/is/a/url/segment //Segment based URL
http://domain.com/?type=message&message=hi //Querystring based url

For added flexability, we can choose whether we want to make this change application-wide or controller-specific.

1 – Application-wide (This will affect every controller):
In system/application/config.php find and modify the following two lines:

//Change from 'AUTO' to 'PATH_INFO' to allow querystrings
$config['uri_protocol'] = 'PATH_INFO';
 
//Change from 'FALSE' to 'TRUE' to allow querystrings
$config['enable_query_strings'] = TRUE;

2 – Controller-specific (This will only affect a single controller and not your entire application)
In system/application/config.php find and modify the following line:

//Change from 'AUTO' to 'PATH_INFO' to allow querystrings
$config['uri_protocol'] = 'PATH_INFO';

In the controller you wish to add querystrings to, add into the constructor:

function Welcome()
{
	parent::Controller();
	//Allow querystrings for this constructor
	parse_str($_SERVER['QUERY_STRING'],$_GET);
}

That’s it. To give this a test, create a ‘Welcome’ controller in system/application/controllers/ with the following code:

<?php
 
class Welcome extends Controller {
 
	function Welcome()
	{
		parent::Controller();
 
		//Uncomment this if using controler-specific querystrings
		//parse_str($_SERVER['QUERY_STRING'],$_GET);
	}
 
	function index()
	{
		if ( isset($_GET['message']) )
			echo $this->input->get('message');
		else
			echo 'There is no message';
	}
}

You should now be able to locate http://yoursite.com/welcome/?message=Hello-World

If you’re trying this on a new CodeIgniter installation and are wondering why you’re getting a ‘page not found’ error, make sure you’ve got your .htaccess file in the CodeIgniter root directory:

RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]