Pregunta

Sé que codeIgniter apaga OBTENER los parámetros por defecto.

Pero por tener todo lo que se hace en el POST, no te enfades por la re-enviar solicitudes de datos si cada vez que pulse de nuevo después de que el envío de un formulario?

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

Es un gran problema de seguridad para permitir OBTENER los parámetros demasiado?

¿Fue útil?

Solución

Cuando comencé a trabajar con CodeIgniter, no usar GET realmente me desanimó también. Pero luego me di cuenta de que puede simular parámetros GET manipulando el URI utilizando el Clase de URI . Es fantástico y hace que tus URL se vean mejor.

O si realmente necesita que los GET funcionen, puede poner esto en su controlador:

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

Lo que volverá a colocar las variables en la matriz GET.

Otros consejos

Esto funcionó para mí :

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

$params matriz contiene los parámetros que se pasa después ?carácter

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; 

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

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

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

¡Encontré que los parámetros $ _GET no son realmente necesarios en CI, pero Facebook y otros sitios descargan los parámetros GET al final de los enlaces que serían 404 para mi sitio CI! Al agregar 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 / )

Puede habilitar cadenas de consulta si realmente insiste. En su config.php puede habilitar cadenas de consulta:

$config['enable_query_strings'] = TRUE;

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

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

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

puede evitar esto haciendo una redirección desde la página que procesa el envío de su 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 volverá a cargar esa página y no volverá a enviar el formulario.

Si necesita el primer parámetro, úselo.

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

Y tu segundo parámetro lo necesitas

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

Haga que sus muchos parámetros mejoren el parámetro

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

Un poco fuera de tema, pero estaba buscando una función get en CodeIgniter solo para pasar algunas variables entre controladores y encontrar Flashdata.
ver: http://codeigniter.com/user_guide/libraries/sessions.html
Flashdata le permite crear datos de sesión rápida que solo estarán disponibles para la próxima solicitud del servidor, y luego se borrarán automáticamente.

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 */

mi parámetro es? uid = 4 y obtenlo con:

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

wis

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

Puedes probar esto

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

Aún más fácil:

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

sin embargo, ese complemento es bastante bueno.

Haz esto a continuación. Trabajó para mi. Tomé valores de un cuadro de selección y otro cuadro de texto. Luego, al hacer clic en el botón, tomé todos los datos en la función Javascript y los redirigí usando 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;
        }
    });
});

El código anterior funcionó para mí.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top