0

I have a router class in my php project that works like this:

public function dispatch(){
     foreach ($this->routes as $url => $action) {

        if( $url == $_SERVER['REQUEST_URI'] ){

            if(is_callable($action)) return $action();

            $actionArr = explode('#', $action);
            $controller = 'My\\system\\controllers\\'.$actionArr[0];
            $method = $actionArr[1];

            return (new $controller)->$method();
        }
    }
}

And I define the routes like this:

My\system\classes\Registry::get("Router")->add('/My/admin/','AdminController#index');

So when the URL SERVER/My/admin is called the index method of the AdminController class is called.

My problem: How do I handle query strings?

I'd like to have a page with a form. On submit, the form gets sent to SERVER/My/admin/check, i.e. to the check.php page in the admin folder.

I defined the route like this

My\system\classes\Registry::get("Router")->add('/My/admin/check','AdminController#check');

but the URL isn't found, of course, because the query string is attatched to the URL. How should I handle this best?

1
  • What's your htaccess look like? A lot of router implementations will pass the route (url) into a query parameter meaning you don't need to account for other query parameters. Commented Sep 6, 2022 at 5:39

2 Answers 2

2

Before checking $_SERVER['REQUEST_URI'], remove everything past the first ?, if one is present. Use that value to check if it matches with $url. Something as simple as this will do the trick:

$request = $_SERVER['REQUEST_URI'];
if( ($pos = strpos($request, '?')) !== false) $request = substr($request, 0, $pos);

Any controllers that need to work with query parameters should be able to get them from $_GET, or at worst $_SERVER['QUERY_STRING'].

Sign up to request clarification or add additional context in comments.

Comments

0

This example is from my project, how I handle this.

REQUEST_URI - The URI which was given in order to access this page; for instance, '/index.html'.

$full_router = $_SERVER['REQUEST_URI'];

strtok() splits a string (string) into smaller strings (tokens), with each token being delimited by any character from token.

$router = strtok($full_router, '?'); // This is how you can handle query parameters

Now you can match the URL with if statement

if($router === '/' ){
    include('/pages/home.php');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.