获取 PHP 中的 URL 参数

2022-01-30 00:00:00 url redirect php

我正在尝试将 URL 作为 php 中的 url 参数传递,但是当我尝试获取此参数时,我什么也没得到

我正在使用以下网址形式:

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

我正在努力解决:

$_GET['link'];

但没有返回.有什么问题?

解决方案

$_GET 不是函数或语言结构——它只是一个变量(一个数组).试试:

特别是,它是一个superglobal:一个内置的在由 PHP 填充的变量中,并且在所有范围内都可用(您可以在没有 全局关键字).

由于变量可能不存在,您可以(并且应该)确保您的代码不会触发通知:

或者,如果您想跳过手动索引检查并可能添加进一步的验证,您可以使用 filter 扩展:

最后但同样重要的是,您可以使用 空合并运算符(从 PHP/7.0) 处理丢失的参数:

echo $_GET['link'] ??'后备价值';

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?

解决方案

$_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';

相关文章