How to properly extract get variables

10,221

Solution 1

An easy way:

$token = isset($_GET['token']) ? $_GET['token'] : null;

If token is set it is assigned to $token, otherwise $token is null.

Solution 2

$_GET is an array:

$token = $_GET['token'];

So if you print out, you should see the token part of the query string:

echo "'Token: $token'"; // should display 'Token: 3072420e7e32cbcf304da791537d757342cf5957';

NOTE

If you are trying to use $token to search a mysql database, you need to first escape slashes, to prevent security issues:

$token = mysql_real_escape_string($_GET['token']);

Also, you first need to have a mysql connection before calling mysql_real_escape_string().

NOTE V.2

In your query string, your token will be everything from ?token= until PHP encounters a query key/pair delimiter (typically, & and ;). To wit:

http://www.blahblahblah.com/reset_password.php?token=3072420e7e32cbcf304da791537d757342cf5957&token2=otherstuff

&token2=otherstuff would be another key accessible by $_GET['token2'], so it wouldn't be an issue with $_GET['token'].

Solution 3

So you do actually have an URL string, and want to extract values from that:

$url = "http://www.example.com/reset_pw.php?token=3072420e7e32cbc...";

$p = parse_url($url);          // splits up the url parts
parse_str($p["query"], $get);  // breaks up individual ?var= &vars=

print $get["token"];
Share:
10,221
LightningWrist
Author by

LightningWrist

Updated on June 20, 2022

Comments

  • LightningWrist
    LightningWrist almost 2 years

    I am still somewhat new to php and was wondering the best way to extract a $_GET variable from a url.

    for example how would I capture it out of something like this:

    http://www.blahblahblah.com/reset_password.php?token=3072420e7e32cbcf304da791537d757342cf5957
    

    just want to get everything from the "token=etc..."

    thanks in advance

  • LightningWrist
    LightningWrist about 13 years
    that is what I have been trying but it yields nothing
  • Jared Farrish
    Jared Farrish about 13 years
    You need to post the code you're using then. This is how the $_GET array works.