How to make CodeIgniter accept "query string" URLs?

According to CI's docs, CodeIgniter uses a segment-based approach, for example:

example.com/my/group

If I want to find a specific group (id=5), I can visit

example.com/my/group/5

And in the controller, define

function group($id='') {
    ...
    }

Now I want to use the traditional approach, which CI calls "query string" URL. Example:

example.com/my/group?id=5

If I go to this URL directly, I get a 404 page not found. So how can I enable this?


Solution 1:

For reliable use of query strings I've found you need to do 3 things

  1. In application/config/config.php set $config['enable_query_strings'] = true;
  2. Again in application/config/config.php set $config['uri_protocol'] = "PATH_INFO";
  3. Change your .htaccess to remove the ? (if present) in the rewrite rule

I use the following

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Solution 2:

//Add this method to your (base) controller :
protected function getQueryStringParams() {
    parse_str($_SERVER['QUERY_STRING'], $params);
    return $params;
}


// Example : instagram callback action
public function callback()
{
    $params = $this->getQueryStringParams();
    $code = !empty($params['code']) ? $params['code'] : '';

    if (!empty($code))
    {
        $auth_response = $this->instagram_api->authorize($code);

        // ....  
    }

    // .... handle error
}    

Solution 3:

This might help some people; put this into your controller's constructor to repopulate $_GET on a controller-by-controller basis (e.g. if you are integrating a third party lib that relies on $_GET - such as most PHP OAuth libraries).

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

Solution 4:

You may change URI PROTOCOL in your config file to

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

and

  $config['enable_query_strings'] = FALSE;

It'll accept query strings and allow your URLs. Worked for me :)

Solution 5:

Html:

<a href="?accept=1" class="btn btn-sm btn-success">Accept</a>

Controller Function

if ($this->input->get('accept')!='')
{
    $id = $this->input->get('accept', TRUE );
    $this->camprequests->accept($id);
    redirect('controllername/functionname');
}

Model Function

public function accept($id)
{
    $data = array('status'=>'1');
    $this->db->where('id','1');

    if($this->db->update('tablename',$data)) {

        $this->session->set_flashdata("accpeted","<div class='col-sm-12 alert alert-success'>Accpeted successfully.</div>"); 

    } else { 

        $this->session->set_flashdata("accpeted","<div class='col-sm-12 alert alert-success'>Error..</div>");  
    }
}