Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and disect the query string appended into a url? PHP

Tags:

php

I am trying to develop a PHP class which would enable me to get the query string appended into a url and process it according to the variables passed. How can this be done?

Eg

www.example.com?var1=a&var2=b&var3=c

now I want to get ?var1=a&var2=b&var3=c section and process it based on the variables.

Thanks for your responses

but I want a means by which I can get the whole query string since I wont be sure of the variable names that will be sent into the URL thus the $_GET method wont work properly.

Thanks

like image 245
Stanley Ngumo Avatar asked Dec 17 '25 18:12

Stanley Ngumo


2 Answers

// Current URL: www.example.com?var1=a&var2=b&var3=c
function handleUrl()
{
    $var1 = $_GET['var1']; // now contains 'a'
    $var2 = $_GET['var2']; // now contains 'b'
    $var3 = $_GET['var3']; // now contains 'c'

    return "Querystring now contains $var1 $var2 and $var3";
}

More information at http://php.net/manual/en/reserved.variables.get.php

like image 54
sshow Avatar answered Dec 20 '25 08:12

sshow


If you want access to the URL parameters as a string you can use this:

$_SERVER['QUERY_STRING']

But, I'm not sure how that would be any more useful than $_GET. You said:

I wont be sure of the variable names

You can iterate through the $_GET array with a foreach loop:

foreach ($_GET as $key => $val) {
    echo $key . ": " . $val;
}

However... if you're talking about an arbitrary URL (not necessarily the one which was requested), then the above methods won't work since they obviously won't be in $_GET. Instead you can use parse_url

$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_QUERY);

Output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
arg=value
like image 30
nickf Avatar answered Dec 20 '25 09:12

nickf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!