soren.qvist
soren.qvist

Reputation: 7416

How do I extract query parameters from a URL string in PHP?

Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc, it can be anything. I need to extract the value of a certain query parameter, in this case 'test' (the value 123). Is there a way to do this?

Upvotes: 25

Views: 32914

Answers (3)

Hugo Ferreira
Hugo Ferreira

Reputation: 184

the hostname is optional but is required at least the question mark at the begin of parameter string:

$inputString = '?test=123&random=abc&usersList[]=1&usersList[]=2' ;

parse_str ( parse_url ( $inputString , PHP_URL_QUERY ) , $params );

print_r ( $params );

Upvotes: 1

Rob
Rob

Reputation: 2666

I needed to check an url that was relative for our system so I couldn't use parse_str. For anyone who needs it:

$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);

Upvotes: 2

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

You can use parse_url and parse_str like this:

$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];

parse_url allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc). Then we can parse the query with parse_str.

Upvotes: 66

Related Questions