从 link PHP 获取变量

Getting a variable from a link PHP

我有两个文件,一个叫 test3.php,另一个叫 test4.php。我试图回显文件 test4.php 的 link 中的变量,但它回显了意外的结果。请看一下。

在名为 test3.php 的文件中:

<?php

$text = "Good morning.";

header('Location:test4.php?text=$text');

?>

在名为 test4.php 的文件中:

<?php

$text = $_GET['text'];

echo "$text";

?>

预期回显结果:

"Good morning."

实际回显结果:

$text

我不明白为什么它回显 $text,而不是 "Good morning." 我想到的一件事是,当您使用 header 时,您实际上无法设置变量,所以如果是这种情况,请告诉我。谢谢。

使用

header("Location:test4.php?text=".$text);

变量不在单引号中解析

header('Location:test4.php?text=$text');

因此,您需要使用双引号

header("Location:test4.php?text=$text");

参考文献:

此外,最好在 header 之后添加 exit; 以停止进一步执行,如果您在其下面有更多代码(或将来决定)。

并根据手册使用完整的 http:// 调用

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

脚注,关于 header,根据手册:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.


  • 无论你怎么写,我都在按字面意思使用:

Expected echo result:

"Good morning."

如果您只想回显带有双引号的 "Good morning." 文本,那么您需要在 test4.php 文件中更改以下内容:

echo "$text";

,并使用 \

转义 "
echo "\"$text\"";

在test4.php中:

<?php

$text = $_GET['text'];

echo "$text";

?>

当您引用“$text”时,您正在回显 af 字符串。 您要做的是回显变量:$text.

所以:

<?php

$text = $_GET['text'];

echo $text;

 ?>

...没有引号.. :)

还有:header('Location:test4.php?text=$text');是个婊子,如果你在下面大量代码中使用它...

为了避免麻烦,使用:

echo "<script type='text/javascript'>window.location.href = 'test4.php?text=".$text."';</script>";

改为 ;)