Benedict Lewis
Benedict Lewis

Reputation: 2813

Getting $_GET variable when using mod_rewrite

I am having issues getting $_GET variables with mod_rewrite enabled. I have the following .htaccess:

RewriteEngine On
RewriteRule ^/?Resource/(.*)$ /$1 [L]
RewriteRule ^$ /home [redirect]
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ /app.php?page=$1&query=$2 [L]

and app.php is:

<?php
require("controller.php");
$app = new Controller();

and controller.php is:

<?php
require("model.php");
require("router.php");

class Controller{

//--------Variables------------
    private $model;
    private $router;
//--------Functions------------

    //Constructor
    function __construct(){
        //initialize private variables
        $this->model = new Model();
        $this->router = new Router();

        $page = $_GET['page'];

        //Handle Page Load
        $endpoint = $this->router->lookup($page);
        if($endpoint === false) {
            header("HTTP/1.0 404 Not Found");
        }else {
            $this->$endpoint($queryParams); 
        }
    }
    private function redirect($url){
        header("Location: /" . $url);
    }

    //--- Framework Functions
    private function loadView($view){
        require("views/" . $view . ".php");
    }
    private function loadPage($view){
        $this->loadView("header");
        $this->loadView($view);
        $this->loadView("footer");
    }

    //--- Page Functions
    private function indexPage(){
        $this->loadPage("home");
    }
    private function controlPanel(){
        echo "Query was " . $code;
        /*
        if($this->model->set_token($code)){
            $user = $this->model->instagram->getUser();
        }else{
            echo "There was an error generating the Instagram API settings.";
        }
        */
        $this->loadPage("controlpanel");
    }
    private function autoLike(){
        $this->loadPage("autolike");
    }
    private function about(){
        $this->loadPage("about");
    }
}

So an example of a URL that I might have is /app.php?page=controlpanel&query=null which would be rewritten as /controlpanel. The problem I have is that I have another page which sends a form to /controlpanel resulting in a URL like /controlpanel?code=somecode.

What I am trying to do is get $_GET['code'] and I cannot seem to do this. Can anyone help? Apologies in advance for a bit of a code dump.

Upvotes: 1

Views: 156

Answers (1)

Orangepill
Orangepill

Reputation: 24655

Change

RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ /app.php?page=$1&query=$2 [L]

to

RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ /app.php?page=$1&query=$2 [L,QSA]

QSA is to append the query string

From the docs

"When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined."

Upvotes: 4

Related Questions