Serpentdriver
Serpentdriver

Reputation: 103

PHP - How to get $_GET Parameter without value

I need to know how to get the $_GET parameter from requested url. If I use for example

$url = $_SERVER['REQUEST_URI'];
$parse_url = parse_url($url, PHP_URL_QUERY);

echo $parse_url; will output query=1, but I need only the parameter not parameter AND value to check if parameter is in array.

Upvotes: 2

Views: 3292

Answers (4)

jspit
jspit

Reputation: 7683

The Arry $_GET contains all needed informations. $ _SERVER ['REQUEST_URI'] and parse_url not needed. As an example I have the following browser line:

http://localhost/php/test.php?par&query=1

Let's see what $ _GET contains

echo '<pre>';
var_export($_GET);

Output

array (
  'par' => '',
  'query' => '1',
) 

With array_keys() I get all keys.

$keys = array_keys($_GET);
var_export($keys);

Output:

array (
  0 => 'par',
  1 => 'query',
) 

The first key I get with (see also comment from @bobble bubble)

echo $keys[0];  //par

or

echo key($_GET);

With array_key_exists () I can check whether a key is available.

if(array_key_exists('query',$_GET)){
  echo 'query exists';
}

Upvotes: 0

A. Cedano
A. Cedano

Reputation: 919

You can use basename() too, it Returns trailing name component of path. For example:

$lastPart=explode("=",basename('http://yourdomain.com/path/query=1'));
echo $lastPart[0];

Output

query

Upvotes: -1

NVRM
NVRM

Reputation: 13047

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"] != ""){ ... }

Upvotes: 2

Stuart
Stuart

Reputation: 6785

Something like:

// Example URL: http://somewhere.org?id=42&name=bob

// An array to store the parameters
$params = array();
parse_str($_SERVER['QUERY_STRING'], $params);

// Access what you need like this:
echo 'ID: ' .$params['id']; 

Upvotes: 1

Related Questions