微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何传递和使用php中的header()传递的变量从1个文件到另一个文件

我在“$variables”中有一个变量数组,它包含如下数据: –

$variables['firstname'] = "Sachin"; (say the user filled in these)
$variables['lastname'] = "Tendulkar";
$variables['firstname'] = "SachinTendulkar";

现在,在同一页面上验证后,我使用: –

header("Location:http://localhost/PHPSample/target.PHP");

用户重定向到另一个页面“target.PHP”. “header()”函数中的语法是什么,将数组$variables的值传递给“target.PHP文件,并在“target.PHP文件中使用这些值来显示用户输入的内容

target.PHP代码

<?PHP
echo "<h2>Your Input:</h2>";
echo "Firstname:" .; //Here what needs to be written after . and before ; to use the values passed from the other file
echo "<br>";
echo "Lastname:" .;
echo '<br>';
echo "Username:" .;
echo '<br>';
?>

我在某处读到我们必须在“target.PHP”中使用$_GET [‘firstname’]来使用这些值.如果它是正确的那么这是不安全的,因为$_GET不应该用于敏感信息,如用户名,密码等?

解决方法:

由于您需要通过header()传递数组,请使用http_build_query:

header("Location:http://localhost/PHPSample/target.PHP?vals=" . http_build_query($arr));

请注意,重定向本质上不能执行POST.它将导致新的GET请求,这意味着您必须在URL中传递数据.如果你有一个非常大的网址,你几乎可以保证丢失大部分网址,因为网址有长度限制.

但是,如果它很短,您还可以尝试以下方法

header("Location:http://localhost/PHPSample/target.PHP?vals=" . urlencode(serialize($variables)));

您可以访问target.PHP文件中的数组值:

$Values= unserialize(urldecode($_GET['vals']));
echo "<h2>Your Input</h2>";
foreach($Values as $key => $value) {
  echo $key." : ".$value."<br>";
}

除此以外

<?PHP
$Values= unserialize(urldecode($_GET['vals']));
echo "<h2>Your Input:</h2>";
echo "Firstname:" .$Values['firstname']; //Here what needs to be written after . and before ; to use the values passed from the other file
echo "<br>";
echo "Lastname:" .$Values['lastname'];
echo '<br>';
echo "Username:" .$Values['username'];
echo '<br>';
?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐