13

Hey, say I have a url just being passed through my php is there any easy way to get some GET variables that are being passed through it? It's not the actual url of the page or anything.

like a just have a string containing

http://www.somesite.com/index.php?url=var&file_id=var&test=var

Whats the best way to get the values for those variables?

1

5 Answers 5

39

parse_str(parse_url($url, PHP_URL_QUERY), $array), see the manpage for parse_str for more info.

Sign up to request clarification or add additional context in comments.

Comments

16
$href = 'http://www.somesite.com/index.php?url=var&file_id=var&test=var';

$url = parse_url($href);
print_r($url);
/* Array
(
    [scheme] => http
    [host] => www.somesite.com
    [path] => /index.php
    [query] => url=var&file_id=var&test=var
) */

$query = array();
parse_str($url['query'], $query);

print_r($query);
/* Array
(
    [url] => var
    [file_id] => var
    [test] => var
) */

3 Comments

Does not seem to work if you have a CSS instead of PHP file. Might be doing something wrong.
php code never works in css files (unless you have registered css files to be application/x-httpd-php or equivalent in your server configuration, which you probably shouldn't.
Yes I understand. What I meant to say is that I have a CSS file referred with style.css?v=12345, v being a version number to force a refresh of the cache browser side. What I wanted to do was remove or extract the parameter. Got it working the way I want now.
4

It's actually a lot easier than writing any custom functions.

$queryStr = $_SERVER['QUERY_STRING'];

1 Comment

that takes both get and post vars, right? In that case you might end up with a lot more arguments than just the get vars from the URL. If you in stead use REDIRECT_QUERY_STRING then you only get the args from URL.
0

I'd use something like:

preg_match_all('/(\?|&)([^=]+=[^&]*)/', $string , $matches);

then

print_r($matches[2]);
/*
Array
(
    [0] => url=var
    [1] => file_id=var
    [2] => test=var
)
*/

Hope it works 4 u.

Comments

-1

A quick google for "PHP GET" gives this page from w3schools:

http://www.w3schools.com/php/php_get.asp

1 Comment

He's not asking about retrieving the parameters of the current page. Rather, he wants to parse the query string from some arbitrary URL, i.e. from some string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.