Skip to content
Advertisement

Fetching url query parameters inside php case

I have below index.php file which will handle all routes:

<!DOCTYPE html>
<html>
<body>

    <?php
    $request=$_SERVER['REQUEST_URI'];
switch($request){
    case '/': require __DIR__.'/index1.php';break;
    case '/home':require __DIR__.'/views/home.php';break;
    default: echo("wrong");}
?>
</body>
</html>

And below file is home.php:

<html>
<body>
<?php
$str=$_SERVER['QUERY_STRING'];
echo($str);
?>
</body>
</html>

In case of no query strings, the above setup works fine. But how will I include the condition in which user hits 127.0.0.1/home?1234. In this case, any case statement will become invalid and it will return wrong. How would I change this so that it goes to appropriate route along with query string?

Thanks in advance!

Advertisement

Answer

Do not use regex or string functions. Use parse_url to extract the path (or just about any portion) from a URL:

$path = parse_url("/home?1234", PHP_URL_PATH);
# $path will be "/home"
switch ($path) {
   ...
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement