GET URL parameter in PHP

Feras Odeh picture Feras Odeh · May 4, 2011 · Viewed 659.2k times · Source

I'm trying to pass a URL as a url parameter in php but when I try to get this parameter I get nothing

I'm using the following url form:

http://localhost/dispatch.php?link=www.google.com

I'm trying to get it through:

$_GET['link'];

But nothing returned. What is the problem?

Answer

Álvaro González picture Álvaro González · May 4, 2011

$_GET is not a function or language construct—it's just a variable (an array). Try:

<?php
echo $_GET['link'];

In particular, it's a superglobal: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the global keyword).

Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:

<?php
if (isset($_GET['link'])) {
    echo $_GET['link'];
} else {
    // Fallback behaviour goes here
}

Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:

<?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);

Last but not least, you can use the null coalescing operator (available since PHP/7.0) to handle missing parameters:

echo $_GET['link'] ?? 'Fallback value';