Reputation: 177
I'm developing an MVC web app, and for its router to function I need to parse the query string, for which I need to load the URL into a variable in the first place. How do I achieve this with the PHP's built-in server?
I use PHP 7.3.9 at the moment, but as far as I can tell, the issue is persistent across all versions of a built-in server.
If I use Apache to run this app, everything is simple, all I need to do is
$uri = $_SERVER['QUERY_STRING'];
and I'm good to go, everything works just fine.
However, if I use PHP's built-in web server, I get an error saying:
Undefined index: QUERY_STRING in /path_to_my_project/public/index.php on line 22
I tried googling around and found this pull request suggesting that such a variable truly doesn't exist in the PHP's built-in web server.
So my question is: how do I obtain the query string for my router if I run the built-in server, where $_SERVER['QUERY_STRING']
doesn't exist?
Upvotes: 4
Views: 5394
Reputation: 6703
You can get the same result by using REQUEST_URI
, if this is available:
function getServerQueryString()
{
if(isset($_SERVER['QUERY_STRING']))
{
return $_SERVER['QUERY_STRING'];
}
elseif(isset($_SERVER['REQUEST_URI']))
{
$xpl = explode('/', $_SERVER['REQUEST_URI']);
$baseName = $xpl[array_key_last($xpl)];
if(strpos($baseName, '?') !== false)
{
return substr($baseName, strpos($baseName, '?')+1);
}
}
return null;
}
echo $uri = getServerQueryString();
Some examples:
pageName.php?par1=val1&par2=val2...
// Output:
par1=val1&par2=val2...
pageName.php?
// Output:
// empty
/some/path
// Output:
// empty
Upvotes: 4
Reputation: 53553
$_SERVER['QUERY_STRING']
is only present when there is actually a query string on the request. You can avoid this issue by using array_key_exists():
if (array_key_exists('QUERY_STRING', $_SERVER)) {
$uri = $_SERVER['QUERY_STRING'];
} else {
$uri = '';
}
Or isset():
if (isset('QUERY_STRING', $_SERVER)) {
$uri = $_SERVER['QUERY_STRING'];
} else {
$uri = '';
}
Or (simplest) via the null coalesce operator:
$uri = $_SERVER['QUERY_STRING'] ?? '';
Note that you're probably getting this error on Apache too, you just don't notice it because it doesn't normally get dumped to the console.
Upvotes: 2