HOWTO · PHP
從操作頁面返回帶有 ID 的文章標籤
本教程演示如何轉到另一個 php 頁面並返回到相同的操作標記。
假設你在登入表單中,並且你輸入了錯誤的資訊;在這種情況下,你可能希望返回登入頁面。
PHP 有一個內建函式 header(),將頁面重定向到特定頁面。
但是,如果登入頁面位於頁面底部或中間某處怎麼辦。
在這種情況下,我們可以定位標籤的 id 並將其放入 URL。我們可以將 Html 文章標籤用於登入表單的獨立專案部分。
使用 PHP 標頭返回帶有 ID 的特定文章標籤
我們使用兩種不同的文章標籤,它們具有不同的 id,一個帶有內容和登入表單。當我們提交時,我們想回到登入部分。
index.php 頁面:
<!DOCTYPE html>
<html>
<head>
<style>
p {
font-size: 100px;
}
#email {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
input[type=email], input[type=password] {
width: 100%;
padding: 10px 18px;
box-sizing: border-box;
margin: 8px 0;
display: inline-block;
border: 3px solid #8fbc8f ;
}
button {
background-color: #8fbc8f;
color: white;
margin: 8px 0;
cursor: pointer;
padding: 10px 18px;
border: none;
width: 100%;
}
</style>
</head>
<body>
<div id="main">
<article id="paragraph1">
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam."</P
</article>
<article id="email">
<form action="action.php" method="post">
Email: <input type="email" placeholder="example@example.com" >
<br>
Password: <input type="password" placeholder="********">
<br>
<button name="submit" type="submit" value="login" class="login">Login</button>
</form>
</article>
<article id="paragraph2">
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam."</P
</article>
</div>
</body>
</html>
表單操作頁面,action.php:
<script>
alert("This is form action page; please enter the information again, click ok to go back to the login form");
</script>
<?php
//header function is used to redirect the page to a perticular link. we can fetch the id of a tag and redirect the page
$url = 'Refresh:0; url=index.php#email';
header($url);
?>
在 index.php 提交表單後,程式碼將轉到第二頁並將其重定向回 index.php 的登入部分。
輸出:

在這種情況下,我們可以在 action.php 頁面的標頭之前放置任何東西來驗證資料庫中的電子郵件和密碼資訊,以便有條件地重定向。
對於動態重定向,我們可以在 index.php 頁面上使用 javascript 或 jquery 來獲取當前標籤的 id 並將其傳送到 action.php 以將頁面重定向到該標籤。