0

How can I grab an empty parameter name in PHP e.g. http://yoursite.com/?123 > "123" ?

I want to use this as URL shortener to redirect to the ID from the parameter.

Martin
  • 2,007
  • 6
  • 28
  • 44

2 Answers2

0

You have built-in function that will parse your URL parse_url() and string query parser parse_str():

$url = 'http://yoursite.com/?123&a=b&abc=';
$parsed = parse_url($url);
parse_str($parsed['query'], $query);
var_dump($query);

demo

Keys in array $query that have empty string as value, are the keys you are looking for.

$filtered = array_filter($query, function($v) { return empty($v); });
#$filtered = array_keys($filtered);
print_r($filtered);

demo

Kornel
  • 97,764
  • 37
  • 219
  • 309
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • Thanks, but as dimimpou pointed out, `$_SERVER['QUERY_STRING']` does just fine. Added is_numeric() and whoop! – Martin Jan 03 '14 at 00:37
  • @Martin: I miss-understood the question, I thought you have URL saved in the variable. p.s. What if someone adds some custom parameters to the URL? Like `?test=abc&123` ? – Glavić Jan 03 '14 at 00:38
  • Oh, sorry. Then he fails which is fine for being a hacker :) – Martin Jan 03 '14 at 00:41
  • @Martin: `hacker`, lol ;) Some links are changed by google or FB, who append there own parameters. You should check that case scenario, and not leave it in the 'air' ;) – Glavić Jan 03 '14 at 00:44
0

Use array_keys to fetch all keys.

var_dump(array_keys($_GET));

array(1) { 0 => "123" }

"123" will also appear if you iterate over $_GET, like with foreach.

Halcyon
  • 57,230
  • 10
  • 89
  • 128