Saturday, October 8, 2011

Both sement based and query string(GETmethod) variables in url ofcodeigniter site


By default codeigniter doesn't support query string or get method variables, we can use only segment based url. To enable both segment base and query string (GET method) variables, you need to follow the upcoming steps...

1 ) In yout codeigniter config file change the uri_protocol as specified bellow,

application/config/config.php

$config['uri_protocol']    = 'AUTO';

to

$config['uri_protocol']    = 'PATH_INFO';
//  OR

$config['uri_protocol']    = 'ORIG_PATH_INFO';

Some servers does not support 'PATH_INFO' as 'uri_protocol'. Then use 'ORIG_PATH_INFO'.

2 ) In your controller where you want to use query string variable, add the following line in the controller's constructor,

parse_str($_SERVER['QUERY_STRING'],$_GET);

3 ) Now, you are able to use the query string variables in your methods of the controller like given below,

application/controllers/search.php

class Search extends CI_Controller{
function __construct(){
parent::__construct();
parse_str($_SERVER['QUERY_STRING'],$_GET);
}
function result(){
echo "Search result for Name:".$_GET['name']." and Age:".$_GET['age'];
}
}

If your url is,

http://localhost/tinywall/search/result/?name=David&age=22

The above code prints,

Search result for Name:David and Age:22

No comments:

Post a Comment