无法使用 _GET 获取 URL 参数

问题描述

第一次发帖,我在使用 PHP 方面还很陌生,所以请不要打扰我。如果这需要进一步解释,请告诉我。

我有一个页面(我们称之为 page1.PHP),其中声明了以下全局变量

$online = true;

当点击 page1.PHP 上的链接时,我想将一个参数(称为 方法)传递到下一页(我们称之为 page2.PHP)。 PHP)。如果专门通过 page1.PHP 中的链接访问 page2.PHP,我希望它加载此参数并触发特定行为。

更新:21 年 3 月 16 日添加 page1.PHP 上的链接包含在一个用于多个页面的模板文件中。因此,如果页面具有 $online = true全局变量,我使用了 PHP if 语句将参数附加到链接

<a href="page2.PHP<?PHP if(isset(GLOBALS['online'])) {?>?method=online<?PHP } ?>"?link</a>

到目前为止,我已经成功(我认为)将参数传递给 page2.PHP (page2.PHP?method=online)。在 page2.PHP 的顶部,我使用以下代码将此参数的值分配给名为 $method 的变量:

$method = $_GET['method'];

我预计这会产生 $method = "online" 但不幸的是,当我这样做并尝试 echo $method 时,我收到以下通知

注意:未定义索引:方法在 C:URL\index.PHP 上 第 7 行

当我开始时,这似乎相当简单,但这让我发疯。我错过了什么?提前致谢!

解决方法

这种方式对我有用:

page1.php

<!DOCTYPE html>
<html>
    <body>
        <a href="page2.php?method=online">link</a>
    </body>
</html>

page2.php

<?php 
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);


$method = false; // empty
if(array_key_exists('method',$_GET) and !empty($_GET['method']))
    $method = $_GET['method'];
var_dump($method);
// https://yoururl/page2.php?method=online 
// string(6) "online"
// https://yoururl/page2.php?method=
// bool(false)
// https://yoururl/page2.php
// bool(false)
,

像这样更新你的代码

// if it does not exist.
$method = $_GET['method'] ?? null;

PHP Null coalescing operator
不断尝试和玩弄语言,你的方向是正确的