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


how to pass and use the variables passed through header() in php from 1 file to another

我在"$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的值传递到"targetphp"文件,并使用"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中传递数据。如果你有一个非常大的url,你几乎可以保证会丢失大部分,因为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>';
?>

例如,您传递变量名:"flagtype"及其值="network"

从您想要通过的位置写入头位置代码,

 header("location:anotherfilename.php?flagtype=network&variable2=value2");

语法:

header("location:anotherfilename.php?variablename=valuename&variablename2=value2");

我过去为将一个变量放到另一个页面所做的就是将该变量设置为$_SESSION变量。这将分配任何页面都要访问的变量。

记住在使用任何$_session变量之前启动会话:

session_start();
$_SESSION['userData'] = $variables;

userData是给会话的一个名称,它可以被命名为任何名称,这个名称就是您将用来检索同一会话的名称。关于$_SESSION 的PHP手册

$userDataFromValidation = $_SESSION['userData'];

这样可以避免用户可以用来执行XSS的任何Get请求。

HTTP位置字段接受通用格式的URL,因此可以向其中添加GET参数:

 header('Location: http://domain.com/path/to/file/?parameter1=value1&parameter2=value2');

POST和GET参数都很容易修改,如果您不使用SSL或类似的加密方法,它们就不安全。如果您需要传递一些敏感信息,请使用会话:

session_start();
$_SESSION['parameter'] = 'value';

一般来说,Cookie也不安全。