Skip to content
Advertisement

Error when using “parse_str” … Undefined index: query

I am trying to get the current page URL, which may look something like this:

http://www.example.com/login.php/?redirect=myprofile.php

…and then get everything after the “redirect”. Here is my code so far:

$uri = $_SERVER['REQUEST_URI'];
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//the complete URL is
$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//parse URL and return an array containing the URL components
$url_components = parse_url($url);
//check to see if there is anything after the "?" by looking at "query" in the parsed URL
if (array_key_exists(parse_str($url_components['query'], $params), $url_components))
{
    echo "query exists in parse_str";
}
else { echo "query doesn't exist in parse_str"; } 

However, I keep getting an error if the index query does not exists in the array:

Notice: Undefined index: query

I’ve tried isset:

if (isset(parse_str($url_components['query'], $params)))

which gives me a HTTP ERROR 500 error when loading the page.

and empty gives me the same error as the first.

if (!empty(parse_str($url_components['query'], $params)))

I’m new to PHP, so any help would be much appreciated.

Advertisement

Answer

You don’t want to be checking the function call returns. You want to check that the query index exists. You can achieve that with:

$url = 'http://www.example.com/login.php/?redirect=myprofile.php';
$url_components = parse_url($url);
if (!empty($url_components['query'])){
    parse_str($url_components['query'], $params);
    print_r($params);
} else { 
    echo "query doesn't exist in parse_str";
}

parse_str can then be used when you have the query index.

https://3v4l.org/Vt3aa

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement