Parsing Url Query in PHP

Parse query string into an array

You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.

$get_string = "pg_id=2&parent_id=2&document&video";

parse_str($get_string, $get_array);

print_r($get_array);

PHP: Best way to parse URL query without variable name?

If you are sure that nothing malicious would be passed (or you are just testing), then you could do something like:

$output = eval('return ' . parse_url($_SERVER['REQUEST_URI'])['query'] . ';');

echo $output;

Obligatory notice:

Caution
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

However, I would advise you use the following method and parse the expression with parser in the linked question:

$exp = parse_url($_SERVER['REQUEST_URI'])['query']; // 1+1

Reading Material

How to evaluate formula passed as string in PHP?

parse_url

eval

How can I get parameters from a URL string?

You can use the parse_url() and parse_str() for that.

$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];

If you want to get the $url dynamically with PHP, take a look at this question:

Get the full URL in PHP

How to parse a PHP URL Querystring and get the param values

What you are looking for is parse_str

$queryString = "test=1&foo=bar";
parse_str($queryString, $out);
echo '<pre>'.print_r($out, 1).'</pre>';

outputs:

Array
(
[test] => 1
[foo] => bar
)

Demo: http://codepad.viper-7.com/pQ7Bx6

Fetching url query parameters inside php case

Do not use regex or string functions. Use parse_url to extract the path (or just about any portion) from a URL:

$path = parse_url("/home?1234", PHP_URL_PATH);
# $path will be "/home"
switch ($path) {
...

PHP - How to get $_GET Parameter without value

Based on your example, simply exploding the = might quickly suits your need.

$url = $_SERVER['REQUEST_URI'];
$parse_url = parse_url($url, PHP_URL_QUERY);
$queryparam = explode("=", $parse_url);
echo $queryparam[0];
/* OUTPUT query */

if (in_array($queryparam[0], $array_of_params)){ ... }

But you can simply achieve the same thing like this:

if (@$_GET["query"] != ""){ ... }


Related Topics



Leave a reply



Submit