Home > Mobile >  Handling PHP URL and GET requests
Handling PHP URL and GET requests

Time:02-20

I am currently parsing any given url, for example example.com/page/1 or example.com/api/info/1, by exploding the URL:

$REQ = explode('/', $_SERVER['REQUEST_URI']);
array_shift($REQ);
$REQ = array_filter($REQ, function($value) { return $value !== ''; });]

and then accessing its elements in the array like so:

if (count($REQ) > 1 && $REQ[0] == 'page' && $REQ[1] == '1'){
    \\ show page 1
}

But how could I handle (and access via array in the same way) a url that also includes GET elements, such as example.com/page?id=1 or example.com/api/info?=hello ?

I am using nginx and trying files like below:

location / {
    index index.php;
    try_files $uri /index.php?$query_string;
    }

CodePudding user response:

You can parse URL by parse_url function also for query params you can use parse_str function and extract all query parameters.

$url = 'https://example.com/api/info?param1=hello&param2=wrold';

$url_parts = parse_url($url);
var_dump($url_parts);
parse_str($url_parts['query'], $query_params);
var_dump($query_params);

Output:

array(4) {
  ["scheme"]=>
  string(5) "https"
  ["host"]=>
  string(11) "example.com"
  ["path"]=>
  string(9) "/api/info"
  ["query"]=>
  string(25) "param1=hello&param2=wrold"
}
array(2) {
  ["param1"]=>
  string(5) "hello"
  ["param2"]=>
  string(5) "wrold"
}
  • Related