Problem passing parameter via GET MVC

Asked

Viewed 1,237 times

4

I can’t get the figures by GET within a controller or action, example:

Doesn’t work:

example.com/controller/?q=nome
example.com/controller/action/?q=nome

Works:

example.com/?q=nome

Note: POST type parameters work normally

.htaccess

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1
  • You could put an example of PHP code where you try to get the values via GET?

  • I put something like $test = $_GET['query'] in my controller and then pass it to my view.

  • so, but if you’re using ?q=nome url, try to use $_GET['q'] in the code...

  • It was just an example, but it doesn’t work

  • Url = $1 why to use q in the requested link parameter ?

1 answer

1

Here’s what’s going on:

index.php?url=/controller/action/

then its $_GET['url'] is filled with this address url=/controller/action/ !!!

To recover effectively use $_SERVER['REQUEST_URI'] that the same will bring: /controller/action/?q=nome.

Ready now just work with routines that value:

1) Simple example:

$url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI']: '';
if ($url != ''){
    $urls  = explode('/', $url);
    $param = str_replace('?','', end($urls));
    $param = explode('&', $param);
    $params = array();
    foreach($param as $pa){
        $vp = explode('=', $pa);            
        $params[$vp[0]] = sizeof($vp)==2?$vp[1]:NULL;
    }
    //só para imprimir valor na tela!!! var_dump
    var_dump($params);
}

Upshot:

inserir a descrição da imagem aqui


2) Example with parse_url

var_dump(parse_url($_SERVER['REQUEST_URI']));

Upshot:

array(2) { ["path"]=> string(19) "/controller/action/" ["query"]=> string(6) "q=nome" }

Reference

  • 1

    Thanks, I understood how it works, I took a look here in the stack and found the parse_str function, and I did this: $url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';

 $query = parse_url($url, PHP_URL_QUERY);
 parse_str($query, $param);

 return isset($param[$param_name]) ? $param[$param_name] : null;

  • Truth @user3386417, I had forgotten this function ..., I already edited so that it is for all staff!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.