Home > CodeIgniter, PHP > How to Mix Segment and Query String in CodeIgniter

How to Mix Segment and Query String in CodeIgniter

Passing parameter to a web page build with CodeIgniter (CI) can be done by using either POST variables which comes from HTML form or from the URI. But, different from traditional web application, by default CI only recognizes a segment based URI rather than query string format for passing parameter by URI.

In some circumstances we do need to use the query string to pass data to our page, which in this case using PHP global variable $_GET. By default, CI will not allow us to read the content of $_GET variable but instead using the URI class $this->uri->segment(the_segment_number).

To be able to read the content of $_GET variable within a controller we need to do several things.

First, edit the system/application/config/config.php file, locate the line of uri_protocol configuration, and change the value to PATH_INFO.

$config[‘uri_protocol’] = "PATH_INFO";
 

Then, in the controller that we need to read the $_GET variable, put this line inside the controller class constructor.

parse_str($_SERVER[‘QUERY_STRING’],$_GET);

After that, the controller will be able to read the content of the $_GET variable. For example, if we call the controller by using this URI server.com/index.php/controller/abcd?q=1234&js=true, then we can read each of the parameter passed on the URI like this:

 

$abcd=$this->uri->segment(3); // $abcd will contains "abcd"
$q = $_GET['q'] ; // $q will contains "1234"
$js = $_GET['js']; // $js will contains "true"
 

Here is an example of a controller class that can read both URI segment and query string.

<?php
class Mapservices extends Controller {

       
    function Mapservices()
    {
        parent::Controller();
        parse_str($_SERVER[‘QUERY_STRING’],$_GET);

    }
    function lookup()
    {
        $table = $this->uri->segment(3);
       
        $q=$_GET[‘q’];

        // do the required process here…     
    }
}
?>

On the above example, the controller called mapservices could be called by using this URI: server.com/index.php/mapservices/cities?q=bandung .

  • Share/Bookmark
  1. Daniel
    September 24th, 2009 at 20:43 | #1

    Not tested, but should you not be able to use

    $this->input->get()

    ?

    //Daniel

  2. hamza khan
    June 26th, 2010 at 21:48 | #2

    need more details with little few more exmple to explain this concept.
    but thanks for this

  1. No trackbacks yet.
This site uses a Hackadelic PlugIn, Hackadelic SEO Table Of Contents 1.6.0.