Retrieving GET URL Parameters in PHP
Question:
When attempting to access a URL passed as a parameter via a URL form (e.g., http://localhost/dispatch.php?link=www.google.com), the code returns an empty result using $_GET['link'];. What is the issue?
Answer:
The $_GET array is a superglobal that stores GET parameters. However, it functions as a variable rather than a language construct. To access its values, use the echo statement:
echo $_GET['link'];
To handle cases where the parameter is not present, you can employ conditional statements:
if (isset($_GET['link'])) { echo $_GET['link']; } else { // Fallback behavior here }
Alternatively, you can use the filter extension for validation and error handling:
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);
Finally, the null coalescing operator (PHP 7.0 onwards) provides concise fallback behavior:
echo $_GET['link'] ?? 'Fallback value';
The above is the detailed content of Why is my PHP code returning an empty result when trying to retrieve GET URL parameters using `$_GET['link']`?. For more information, please follow other related articles on the PHP Chinese website!