簡體   English   中英

如何傳遞和使用通過 php 中的 header() 傳遞的變量從 1 個文件到另一個文件

[英]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的值傳遞給“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 中傳遞數據。 如果你有一個非常大的 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>';
?>

我過去所做的將變量設置到另一個頁面是將變量設置為$_SESSION變量。 這將分配要被任何頁面訪問的變量。

請記住在使用任何 $_SESSION 變量之前啟動會話:

session_start();

$_SESSION['userData'] = $variables;

userData 是賦予 Sessionsit 的名稱,可以命名為任何名稱,您將使用該名稱來檢索同一個 Session。 $_SESSION 上的 PHP 手冊

$userDataFromValidation = $_SESSION['userData'];

這樣您就可以避免用戶可以用來執行 XSS 的任何 Get 請求。

例如,您傳遞變量名稱:“flagtype”及其值=“network”

從要傳遞的位置編寫標題位置代碼,

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

句法 :

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

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

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

如果您不使用 SSL 或類似的加密方法,POST 和 GET 參數都非常容易修改並且不安全。 如果需要傳遞一些敏感信息,請使用session

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

一般來說,Cookie 也不安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM