PHP 中如何將變數傳遞到下一頁
PHP 變數是等於某一值的符號或名稱。它用於儲存值,例如值,數字,字元或記憶體地址,以便可以在程式的任何部分中使用它們。一個簡單的變數可以在程式的任何部分中使用,但是在它的外部無法訪問,除非它通過 HTML 形式的 GET 和 POST,session 或 cookie 來傳遞它。
通過 HTML 表單使用 GET 和 POST 來傳遞 PHP 變數
HTML 表單是 PHP 最強大的功能之一。任何表單元素將自動可用於表單的 action 目標。
POST 請求
<form action="nextPage.php" method="POST">
<input type="text" name="email">
<input type="text" name="username">
<input type="submit" name="submit">
</form>
獲取資料到 nextPage.php
$username = isset($_POST['username']) ? $_POST['username'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
echo "Username: ".$username;
echo "Email: ".$email;
指令碼的示例輸出:
Username: johndoe
Email: johndoe@gmail.com
上面的示例顯示瞭如何通過 HTML 表單使用 POST 傳遞變數。表單元素需要具有 action 和 method 屬性。action 包含下一頁,在本例中為 nextPage.php。方法可以是 POST 或 GET。然後,你可以使用 $_POST 或 $_GET 訪問 nextPage.php 中的元素。
GET 請求
<?php
$phpVariable = "Dog";
?>
<a href="nextPage.php?data=<?=$phpVariable?>">Bring me to nextPage</a>
這個例子將建立一個 GET 變數,可以在 nextPage.php 中訪問。
例子:
echo $phpVariable = $_GET['phpVariable'];
//output: Dog
可以使用 $_GET 訪問 GET。
另一種方法是在 HTML 表單中新增一個隱藏元素,該元素會提交到下一頁。
例子:
<form action="nextPage.php" method="POST">
<input type="hidden" name="phpVariable" value="Dog">
<input type="submit" name="submit">
</form>
nextPage.php
//Using POST
$phpVariable = $_POST['phpVariable'];
//Using GET
$phpVariable = $_GET['phpVariable'];
//Using GET, POST or COOKIE;
$phpVariable = $_REQUEST['phpVariable'];
你可以將方法從 POST 更改為 GET,以使用 GET 請求。POST 和 GET 對於自動流量來說是不安全的,而且 GET 可以通過前端使用,因此更容易被黑客入侵。
$_REQUEST 可以接受 GET,POST 或 COOKIE。最好在自引用形式上使用 $_REQUEST 來進行驗證。
使用 session 和 cookie 來傳遞 PHP 變數
session 和 cookie 更易於使用,但 session 比 cookie 更為安全,雖然它並不是完全安全。
session:
//page 1
$phpVariable = "Dog";
$_SESSION['animal'] = $phpVariable;
//page 2
$value = $_SESSION['animal'];
session 時,要記住在訪問 $_SESSION 陣列之前在兩個頁面上都新增 session_start()。cookie
//page 1
$phpVariable = "Dog";
$_COOKIE['animal'] = $phpVariable;
//page 2
$value = $_COOKIE['animal'];
cookie 和 session 之間最明顯的區別是,session 將儲存在伺服器端,而 cookie 將客戶端作為儲存端。