-2

I am unable to extract query value from the url dynamically. My url is of the form www.domain.com/script.php?token=4343434 . I want to extract the token value from this url. The token value is generated dynamically. I tried this but not working.

Thanks in advance.

$token = $_GET['token'];

When I print the token it gets printed.

print_r($_GET['token']); //works
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
  • 4
    When you do `$token = $_GET['token'];`, the value (in your case, that's `4343434`) is put into the `$token` variable. Print it with `echo $token;` and you should see it just fine. – Qirel Jul 16 '19 at 05:56
  • ya it's not working for some reason. echo prints nothing. moreover i get token undefined index php notice. however when i use print_r($_GET['token']) it works! – aqualein888 Jul 16 '19 at 06:10
  • Then the `token` parameter of your URL is not defined at that time. If you're using PHP7 or above, you can do `$token = $_GET['token'] ?? 'Token was not set';`. "Undefined index" means the `token` parameter did not exist. Both `echo` and `print_r()` work just fine, the issue must be with how you define the value - in your case, that's passing the `token` parameter in the URL. – Qirel Jul 16 '19 at 06:17
  • 1
    As @Qirel says there is no reason for echo not to work, I think you need to edit the question and show exactly what you're doing as something else is going on – imposterSyndrome Jul 16 '19 at 06:23

3 Answers3

0

You can use a ternary operator,

URL : www.domain.com/script.php?token=4343434

$token = isset($_GET['token']) && !empty($_GET['token']) ? $_GET['token'] : "";
Qirel
  • 25,449
  • 7
  • 45
  • 62
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
  • Checking for both `isset()` and `!empty()` is redundant. All you need is to check for `!empty()`. – Qirel Jul 16 '19 at 06:29
0

Request URL : www.domain.com/script.php?token=4343434

By url parameter using Superglobals $_GET with ternary operator and check whether value is not empty.

$token = isset($_GET["token"]) && !empty($_GET["token"]) ? $_GET["token"] : " ";

If you are using PHP 7+ then ternary operator become more simple like below-

$token = $_GET["token"] ?? " ";

Rahul Gupta
  • 991
  • 4
  • 12
-1

You can use $_REQUEST global variable for it. It doesn't matter that request method is post or get. It will work on both.

Like:

$tokenVal= $_REQUEST['token'];

To check echo $tokenVal;

or see all the value using print_r($_REQUEST);

MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46