
如果您是 PHP 新手,並且想了解如何處理表單和使用會話數(shù)據(jù),本指南適合您。我們將建立一個簡單的項目,使用者可以在其中提交表單、在會話中保存資料、查看資料以及稍後刪除資料。在本教程結(jié)束時,您將了解 PHP 表單處理、驗證、清理和會話的基礎(chǔ)知識。
PHP 中的表單處理是什麼?
表單處理是指捕獲透過 HTML 表單提交的資料並使用 PHP 等伺服器端語言進行處理的過程。這包括:
-
取得表單資料:使用GET或POST等方法。
-
驗證資料:確保輸入符合特定標準。
-
清理資料:清理輸入以防止 XSS 攻擊等安全問題。
-
儲存或處理資料:將其保存在會話、資料庫中,或?qū)⑵滹@示給使用者。
PHP 中的會話是什麼?
會話是為單一使用者跨多個頁面儲存資訊(變數(shù))的一種方式。與 cookie 不同,會話資料儲存在伺服器上,使其更加安全。要在 PHP 中開始使用會話,我們使用 session_start() 函數(shù)。
項目:帶有會話處理的 PHP 表單
我們的專案涉及以下功能:
- 使用者填寫個人資料表。
- 提交的資料經(jīng)過驗證和清理。
- 有效資料儲存在會話中。
- 使用者可以查看或刪除會話資料。
文件結(jié)構(gòu)
這是我們專案的結(jié)構(gòu):
project-folder/
│
├── index.php # Form page
├── submit.php # Form handling and session storage
├── view_session.php # Viewing session data
├── delete_session.php # Deleting session data
第 1 步:建立表單 (index.php)
index.php 檔案包含一個簡單的 HTML 表單,使用者可以在其中輸入詳細資訊。程式碼如下:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form with Session Handling</title>
</head>
<body>
<h1>Submit Your Information</h1>
<!-- Form Section for User Input -->
<form method="get" action="submit.php">
<label for="name">Name:</label><br>
<input type="text">
<hr>
<h3>
Step 2: Handling Form Submission (submit.php)
</h3>
<p>This file processes the submitted form data, validates it, and stores it in a session. Here's the code:<br>
</p>
<pre class="brush:php;toolbar:false"><?php
session_start();
// Initialize error messages and data variables
$error_name = "";
$error_age = "";
$error_email = "";
$error_website = "";
$name = $age = $email = $website = $gender = $comments = $hobbies = "";
// Sanitize and validate the form data
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// Sanitize inputs
$name = htmlspecialchars(trim($_GET['name']));
$age = htmlspecialchars(trim($_GET['age']));
$email = htmlspecialchars(trim($_GET['email']));
$website = htmlspecialchars(trim($_GET['website']));
$gender = isset($_GET['gender']) ? $_GET['gender'] : 'No gender selected.';
$hobbies = isset($_GET['hobbies']) ? $_GET['hobbies'] : ['No hobby selected.'];
$comments = htmlspecialchars(trim($_GET['comments']));
// Validation checks
if (empty($name)) {
$error_name = "Name is required.";
}
if (empty($age) || !filter_var($age, FILTER_VALIDATE_INT) || $age <= 0) {
$error_age = "Valid age is required.";
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_email = "Valid email is required.";
}
if (empty($website) || !filter_var($website, FILTER_VALIDATE_URL)) {
$error_website = "Valid website URL is required.";
}
// If no errors, store data in session
if (empty($error_name) && empty($error_age) && empty($error_email) && empty($error_website)) {
// Store data in session
$_SESSION['name'] = $name;
$_SESSION['age'] = $age;
$_SESSION['email'] = $email;
$_SESSION['website'] = $website;
$_SESSION['gender'] = $gender;
$_SESSION['hobbies'] = implode(", ", $hobbies);
$_SESSION['comments'] = $comments;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission Result</title>
</head>
<body>
<h1>Form Submission Result</h1>
<!-- Show Errors if any -->
<?php
if ($error_name) {
echo "<p>
<hr>
<h3>
Step 3: Viewing Session Data (view_session.php)
</h3>
<p>This file displays session data stored on the server.<br>
</p>
<pre class="brush:php;toolbar:false"><?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Session Data</title>
</head>
<body>
<h1>View Stored Session Data</h1>
<?php
if (isset($_SESSION['name'])) {
echo "<p><strong>Name:</strong> " . $_SESSION['name'] . "</p>";
echo "<p><strong>Age:</strong> " . $_SESSION['age'] . "</p>";
echo "<p><strong>Email:</strong> " . $_SESSION['email'] . "</p>";
echo "<p><strong>Website:</strong> <a href='" . $_SESSION['website'] . "' target='_blank'>" . $_SESSION['website'] . "</a></p>";
echo "<p><strong>Gender:</strong> " . $_SESSION['gender'] . "</p>";
echo "<p><strong>Hobbies:</strong> " . $_SESSION['hobbies'] . "</p>";
echo "<p><strong>Comments:</strong> " . $_SESSION['comments'] . "</p>";
} else {
echo "<p>No session data found!</p>";
}
?>
<br><br>
<a href="index.php">Go Back</a>
</body>
</html>
步驟 4:刪除會話資料 (delete_session.php)
此文件會破壞會話資料。
<?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Deleted</title>
</head>
<body>
<h1>Session Data Deleted</h1>
<p>All session data has been deleted successfully.</p>
<br><br>
<a href="index.php">Go Back</a>
</body>
</html>
涵蓋的關(guān)鍵概念
-
表格處理:
- 使用 GET 方法取得資料。
- 使用條件和過濾器驗證輸入。
- 使用 htmlspecialchars() 清理輸入。
-
會議:
- 使用 session_start() 啟動會話。
- 將資料儲存在
$_SESSION 陣列。
- 查看會話資料。
- 使用 session_unset() 和 session_destroy() 刪除會話資料。
結(jié)論
該專案演示了 PHP 表單處理和會話管理的基礎(chǔ)知識。利用這些概念,您可以建立更複雜的應用程序,安全有效地處理使用者輸入。試驗代碼,並嘗試透過添加資料庫整合或更高級的驗證等功能來擴展它。
編碼愉快! ?
以上是PHP 會話表單處理初學者指南的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!