[html] GET parameters in the URL with CodeIgniter

I know that codeIgniter turns off GET parameters by default.

But by having everything done in POST, don't you get annoyed by the re-send data requests if ever you press back after a form submission?

It annoys me, but I'm not sure if I want to allow GET purely for this reason.

Is it such a big security issue to allow GET parameters too?

This question is related to html codeigniter post get

The answer is


This worked for me :

<?php
$url = parse_url($_SERVER['REQUEST_URI']);
parse_str($url['query'], $params);
?>

$params array contains the parameters passed after the ? character


GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.


A little bit out of topic, but I was looking for a get function in CodeIgniter just to pass some variables between controllers and come across Flashdata.
see : http://codeigniter.com/user_guide/libraries/sessions.html
Flashdata allows you to create a quick session data that will only be available for the next server request, and are then automatically cleared.


You can Try this

$this->uri->segment('');

You can enable query strings if you really insist. In your config.php you can enable query strings:

$config['enable_query_strings'] = TRUE;

For more info you can look at the bottom of this Wiki page: http://codeigniter.com/user_guide/general/urls.html

Still, learning to work with clean urls is a better suggestion.


Even easier:

curl -X POST -d "param=value&param2=value" http://example.com/form.cgi

that plugin's pretty cool though.


"don't you get annoyed by the re-send data requests if ever you press back after a form submission"

you can get around this by doing a redirect from the page that processes your form submission to the success page. the last "action" was the loading of the success page, not the form submission, which means if users do an F5 it will just reload that page and not submit the form again.


parse_str($_SERVER['QUERY_STRING'],$_GET); ONLY worked for me after I added the following line to applications/config/config.php:

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

I found $_GET params not to really be necessary in CI, but Facebook and other sites dump GET params to the end of links which would 404 for my CI site!! By adding the line above in config.php, those pages worked. I hope this helps people!

(from https://web.archive.org/web/20101227060818/http://www.maheshchari.com/work-to-get-method-on-codeigniter/)


MY_Input.php :

<?php
// this class extension allows for $_GET access
class MY_Input extends CI_input {

    function _sanitize_globals()
    {
        // setting allow_get_array to true is the only real modification
        $this->allow_get_array = TRUE;

        parent::_sanitize_globals();
    }

}
/* End of file MY_Input.php */
/* Location: .application/libraries/MY_Input.php */

MY_URI.php :

<?php
/*
 | this class extension allows for $_GET access by retaining the
 | standard functionality of allowing query strings to build the 
 | URI String, but checks if enable_query_strings is TRUE
*/
class MY_URI extends CI_URI{

    function _fetch_uri_string()
    {
        if (strtoupper($this->config->item('uri_protocol')) == 'AUTO')
        {
            // If the URL has a question mark then it's simplest to just
            // build the URI string from the zero index of the $_GET array.
            // This avoids having to deal with $_SERVER variables, which
            // can be unreliable in some environments
            //
            //  *** THE ONLY MODIFICATION (EXTENSION) TO THIS METHOD IS TO CHECK 
            //      IF enable_query_strings IS TRUE IN THE LINE BELOW ***
            if ($this->config->item('enable_query_strings') === TRUE && is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '')
            {
                $this->uri_string = key($_GET);
                return;
            }

            // Is there a PATH_INFO variable?
            // Note: some servers seem to have trouble with getenv() so we'll test it two ways
            $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
            if (trim($path, '/') != '' && $path != "/".SELF)
            {
                $this->uri_string = $path;
                return;
            }

            // No PATH_INFO?... What about QUERY_STRING?
            $path =  (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
            if (trim($path, '/') != '')
            {
                $this->uri_string = $path;
                return;
            }

            // No QUERY_STRING?... Maybe the ORIG_PATH_INFO variable exists?
            $path = str_replace($_SERVER['SCRIPT_NAME'], '', (isset($_SERVER['ORIG_PATH_INFO'])) ? $_SERVER['ORIG_PATH_INFO'] : @getenv('ORIG_PATH_INFO'));
            if (trim($path, '/') != '' && $path != "/".SELF)
            {
                // remove path and script information so we have good URI data
                $this->uri_string = $path;
                return;
            }

            // We've exhausted all our options...
            $this->uri_string = '';
        }
        else
        {
            $uri = strtoupper($this->config->item('uri_protocol'));

            if ($uri == 'REQUEST_URI')
            {
                $this->uri_string = $this->_parse_request_uri();
                return;
            }

            $this->uri_string = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);
        }

        // If the URI contains only a slash we'll kill it
        if ($this->uri_string == '/')
        {
            $this->uri_string = '';
        }
    }

}
/* End of file MY_URI.php */
/* Location: .application/libraries/MY_URI.php */

Even easier:

curl -X POST -d "param=value&param2=value" http://example.com/form.cgi

that plugin's pretty cool though.


Now it works ok from CodeIgniter 2.1.0

    //By default CodeIgniter enables access to the $_GET array.  If for some
    //reason you would like to disable it, set 'allow_get_array' to FALSE.

$config['allow_get_array']      = TRUE; 

You can Try this

$this->uri->segment('');

This worked for me :

<?php
$url = parse_url($_SERVER['REQUEST_URI']);
parse_str($url['query'], $params);
?>

$params array contains the parameters passed after the ? character


If your your need to first parameter use it.

$this->uri->segment('3');

And your need second parameter use it

$this->uri->segment('4');

Have your many parameter enhance parameter


allesklar: That is slightly misleading, as scripts and bots can POST data nearly as easily as sending a normal request. It's not a secret, it's part of HTTP.


my parameter is ?uid=4 and get it with:

$this->uid = $this->input->get('uid', TRUE);
  echo $this->uid;

wis


You simply need to enable it in the config.php and you can use $this->input->get('param_name'); to get parameters.


A little bit out of topic, but I was looking for a get function in CodeIgniter just to pass some variables between controllers and come across Flashdata.
see : http://codeigniter.com/user_guide/libraries/sessions.html
Flashdata allows you to create a quick session data that will only be available for the next server request, and are then automatically cleared.


allesklar: That is slightly misleading, as scripts and bots can POST data nearly as easily as sending a normal request. It's not a secret, it's part of HTTP.


You can enable query strings if you really insist. In your config.php you can enable query strings:

$config['enable_query_strings'] = TRUE;

For more info you can look at the bottom of this Wiki page: http://codeigniter.com/user_guide/general/urls.html

Still, learning to work with clean urls is a better suggestion.


GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.


If your your need to first parameter use it.

$this->uri->segment('3');

And your need second parameter use it

$this->uri->segment('4');

Have your many parameter enhance parameter


"don't you get annoyed by the re-send data requests if ever you press back after a form submission"

you can get around this by doing a redirect from the page that processes your form submission to the success page. the last "action" was the loading of the success page, not the form submission, which means if users do an F5 it will just reload that page and not submit the form again.


This function is identical to the post function, only it fetches get data:

$this->input->get()

https://www.codeigniter.com/user_guide/libraries/input.html


Do this below. Worked for me. I took values from a select box and another textbox. Then on button click I took the entire data in Javascript function and redirected using javascript.

//Search Form
$(document).ready (function($){
    $("#searchbtn").click(function showAlert(e){
        e.preventDefault();
        var cat = $('#category').val();
        var srch = $('#srch').val();

        if(srch==""){
            alert("Search is empty :(");
        }
        else{
            var url = baseurl+'categories/search/'+cat+'/'+srch;            
            window.location.href=url;
        }
    });
});

The above code worked for me.


MY_Input.php :

<?php
// this class extension allows for $_GET access
class MY_Input extends CI_input {

    function _sanitize_globals()
    {
        // setting allow_get_array to true is the only real modification
        $this->allow_get_array = TRUE;

        parent::_sanitize_globals();
    }

}
/* End of file MY_Input.php */
/* Location: .application/libraries/MY_Input.php */

MY_URI.php :

<?php
/*
 | this class extension allows for $_GET access by retaining the
 | standard functionality of allowing query strings to build the 
 | URI String, but checks if enable_query_strings is TRUE
*/
class MY_URI extends CI_URI{

    function _fetch_uri_string()
    {
        if (strtoupper($this->config->item('uri_protocol')) == 'AUTO')
        {
            // If the URL has a question mark then it's simplest to just
            // build the URI string from the zero index of the $_GET array.
            // This avoids having to deal with $_SERVER variables, which
            // can be unreliable in some environments
            //
            //  *** THE ONLY MODIFICATION (EXTENSION) TO THIS METHOD IS TO CHECK 
            //      IF enable_query_strings IS TRUE IN THE LINE BELOW ***
            if ($this->config->item('enable_query_strings') === TRUE && is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '')
            {
                $this->uri_string = key($_GET);
                return;
            }

            // Is there a PATH_INFO variable?
            // Note: some servers seem to have trouble with getenv() so we'll test it two ways
            $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
            if (trim($path, '/') != '' && $path != "/".SELF)
            {
                $this->uri_string = $path;
                return;
            }

            // No PATH_INFO?... What about QUERY_STRING?
            $path =  (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
            if (trim($path, '/') != '')
            {
                $this->uri_string = $path;
                return;
            }

            // No QUERY_STRING?... Maybe the ORIG_PATH_INFO variable exists?
            $path = str_replace($_SERVER['SCRIPT_NAME'], '', (isset($_SERVER['ORIG_PATH_INFO'])) ? $_SERVER['ORIG_PATH_INFO'] : @getenv('ORIG_PATH_INFO'));
            if (trim($path, '/') != '' && $path != "/".SELF)
            {
                // remove path and script information so we have good URI data
                $this->uri_string = $path;
                return;
            }

            // We've exhausted all our options...
            $this->uri_string = '';
        }
        else
        {
            $uri = strtoupper($this->config->item('uri_protocol'));

            if ($uri == 'REQUEST_URI')
            {
                $this->uri_string = $this->_parse_request_uri();
                return;
            }

            $this->uri_string = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);
        }

        // If the URI contains only a slash we'll kill it
        if ($this->uri_string == '/')
        {
            $this->uri_string = '';
        }
    }

}
/* End of file MY_URI.php */
/* Location: .application/libraries/MY_URI.php */

Do this below. Worked for me. I took values from a select box and another textbox. Then on button click I took the entire data in Javascript function and redirected using javascript.

//Search Form
$(document).ready (function($){
    $("#searchbtn").click(function showAlert(e){
        e.preventDefault();
        var cat = $('#category').val();
        var srch = $('#srch').val();

        if(srch==""){
            alert("Search is empty :(");
        }
        else{
            var url = baseurl+'categories/search/'+cat+'/'+srch;            
            window.location.href=url;
        }
    });
});

The above code worked for me.


GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.


You simply need to enable it in the config.php and you can use $this->input->get('param_name'); to get parameters.


This function is identical to the post function, only it fetches get data:

$this->input->get()

https://www.codeigniter.com/user_guide/libraries/input.html


Now it works ok from CodeIgniter 2.1.0

    //By default CodeIgniter enables access to the $_GET array.  If for some
    //reason you would like to disable it, set 'allow_get_array' to FALSE.

$config['allow_get_array']      = TRUE; 

my parameter is ?uid=4 and get it with:

$this->uid = $this->input->get('uid', TRUE);
  echo $this->uid;

wis


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to codeigniter

DataTables: Cannot read property 'length' of undefined How to set time zone in codeigniter? php codeigniter count rows CodeIgniter: 404 Page Not Found on Live Server Only variable references should be returned by reference - Codeigniter How to pass a parameter like title, summary and image in a Facebook sharer URL How to JOIN three tables in Codeigniter how to get the base url in javascript How to get id from URL in codeigniter? How to disable PHP Error reporting in CodeIgniter?

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?