OBTENER parámetros en la URL con CodeIgniter


Sé que CodeIgniter desactiva los parámetros GET por defecto.

Pero al tener todo hecho en POST, ¿no te molesta el reenvío de solicitudes de datos si alguna vez presionas atrás después de un envío de formulario?

Me molesta, pero no estoy seguro de si quiero permitir OBTENER puramente por esta razón.

¿Es un problema de seguridad tan grande permitir parámetros GET también?

Author: Jon Winstanley, 2008-12-02

16 answers

Cuando empecé a trabajar con CodeIgniter, no usar GET realmente me desconcertó también. Pero luego me di cuenta de que puedes simular los parámetros GET manipulando el URI usando la clase URI incorporada . Es fantástico y hace que tus URL se vean mejor.

O si realmente necesitas que funcione, puedes poner esto en tu controlador:

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

Que pondrá las variables de nuevo en la matriz GET.

 57
Author: Jelani Harris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-02 17:36:36

Esto funcionó para mí :

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

$params array contiene los parámetros pasados después del ? carácter

 13
Author: Roberto Gerola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-20 13:25:32

Ahora funciona bien desde 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; 
 11
Author: almix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-01 18:49:52

Esta función es idéntica a la función post, solo que obtiene los datos get:

$this->input->get()

Http://ellislab.com/codeigniter/user-guide/libraries/input.html

 10
Author: Murtaza Baig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 19:06:13

Simplemente necesita habilitarlo en la configuración.php y puede usar $this->input->get('param_name'); para obtener parámetros.

 8
Author: Sumit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-09 07:00:50

parse_str($_SERVER['QUERY_STRING'],$_GET); SOLO funcionó para mí después de agregar la siguiente línea a applications/config/config.php:

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

He encontrado par _GET params no ser realmente necesario en CI, pero Facebook y otros sitios de volcado OBTENER params al final de los enlaces que sería 404 para mi sitio de CI!! Añadiendo la línea anterior en config.php, esas páginas funcionaron. Espero que esto ayude a la gente!

(de http://www.maheshchari.com/work-to-get-method-on-codeigniter/)

 6
Author: Benjamin Sussman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-21 21:23:26

Puede habilitar las cadenas de consulta si realmente insiste. En tu configuración.php puede habilitar cadenas de consulta:

$config['enable_query_strings'] = TRUE;

Para obtener más información, puede ver la parte inferior de esta página Wiki: http://codeigniter.com/user_guide/general/urls.html

Aún así, aprender a trabajar con urls limpias es una mejor sugerencia.

 4
Author: Tomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-27 21:43:11

"no te molestes por las solicitudes de reenvío de datos si alguna vez presionas hacia atrás después de un envío de formulario"

Puedes evitar esto haciendo un redireccionamiento desde la página que procesa el envío de tu formulario a la página de éxito. la última "acción" fue la carga de la página de éxito, no el envío del formulario, lo que significa que si los usuarios hacen un F5 simplemente recargará esa página y no volverá a enviar el formulario.

 2
Author: stef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-13 09:12:20

Si su su necesidad de primer parámetro utilizarlo.

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

Y su necesidad segundo parámetro usarlo

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

Tenga su parámetro muchos mejorar parámetro

 2
Author: Md.Jewel Mia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 19:06:33

Allesklar: Eso es ligeramente engañoso, ya que los scripts y bots pueden PUBLICAR datos casi tan fácilmente como enviar una solicitud normal. No es un secreto, es parte de HTTP.

 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-18 16:55:10

Un poco fuera de tema, pero estaba buscando una función get en CodeIgniter solo para pasar algunas variables entre controladores y venir a través de Flashdata.
véase: http://codeigniter.com/user_guide/libraries/sessions.html
Flashdata le permite crear datos de sesión rápidos que solo estarán disponibles para la siguiente solicitud del servidor y que luego se borrarán automáticamente.

 1
Author: Rwahyudi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-03 03:00:28

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 */
 1
Author: Brian Temecula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-31 18:02:33

Mi parámetro es ?uid = 4 y obtenerlo con:

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

Wis

 1
Author: Ks Sjkjs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-23 19:03:37

Los parámetros GET son almacenados en caché por el navegador web, POST no lo es. Por lo tanto, con un POST no tienes que preocuparte por el almacenamiento en caché, por lo que generalmente se prefiere.

 0
Author: Nick Berardi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-02 17:13:18

Puedes probar esto

$this->uri->segment('');
 0
Author: Inspire Shahin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-30 15:47:30

Aún más fácil:

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

Ese plugin es bastante genial.

 0
Author: devpro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 19:07:10