2010-04-30 279 views

回答

3
header("Location: /login.php"); 

http://php.net/manual/en/function.header.php

+2

我通常在頭後添加'die(「Redirecting ...」);'以確保沒有其他輸出。 – 2010-04-30 02:09:03

+0

@webdestroya - 考慮到用戶是否可以看到重定向失敗,這是否有點讓人誤解? – 2010-04-30 03:52:10

+0

用戶很少看到它,如果他們這樣做,只意味着他們的瀏覽器速度很慢,而不是重定向失敗。 – 2010-04-30 03:53:44

7
header("Location: /login.php"); 
exit; 

exit。不要有史以來忘記這樣做。如果您之後有敏感數據,任何不遵守位置標題的人都可以看到(such as some bots)。

要忘記阻止你,你可以建立一個包裝類型的函數

function redirect($url) { 
    header('Location: ' . $url); 
    exit; 
} 
+0

我不確定Google會不會那樣做,但我可能是錯的。他們遵循301和302的很好......什麼是通過位置與PHP一起發送的默認狀態代碼? – 2010-04-30 03:53:58

+0

@anonymous coward我最近讀了一個'Daily WTF',他們從自定義CMS中刪除了頁面,因爲Internet Archive bot沒有遵循'Location'標題。我混淆了谷歌機器人與他們。 – alex 2010-04-30 03:59:30

+0

等一下,你爲什麼首先輸出敏感數據? – erjiang 2010-05-01 20:50:46

-1
`Header("Location:login.php");` 

或: echo "<meta http-equiv=refresh content='0; url=login.php'>";

或:

echo "<script language='javascript'>"; 
echo "location='login.php';"; 
echo "</script>"; 
+2

永遠不要指望Javascript執行關鍵任務重定向。 – 2010-04-30 03:50:53

0

你可以這樣做:

func.php

<?php 
function EmptyStr($value){ 
    $str = strval($value); 
    $str = str_replace("&nbsp;", "", $str); 
    return (trim($str) == ""); 
} 

function redirect($url) { 
header('Location: ' . $url); 
exit; 
} 
?> 

register.php

<?php 
include("func.php"); 
$username = $_POST["username]; 
$password = $_POST["password"]; 
$email = $_POST["email"]; 
if(!EmptyStr($username) && !EmptyStr($password) && !EmptyStr($email)){ 
    sql = WRITE YOUR SQL SYNTAX HERE TO INSERT THE INPUT TO DB 
    redirect("/login.php"); 
}else{ 
    $_SESSION["ErrMsg"] = "Error! All fields are required."; 
} 

echo $_SESSION["ErrMsg"]; 
$_SESSION["ErrMsg"] = ""; 
?> 
Put your html regsitration form here 

的login.php

<?php 
include("func.php"); 
$username = $_POST["username]; 
$password = $_POST["password"]; 

if(!EmptyStr($username) && !EmptyStr($password)){ 
    sql = WRITE YOUR SQL SYNTAX HERE TO QUERY THE USERNAME AND PASSWORD TO DB 
    if ($rs && !$rs->EOF) { //user found and pass match 
     $_SESSION["username"] = $username; 
     redirect("/main.php"); 
    }else{ 
     $_SESSION["ErrMsg"] = "Invalid username or passsword!"; 
    } 
}else{ 
    $_SESSION["ErrMsg"] = "Error! All fields are required."; 
} 

echo $_SESSION["ErrMsg"]; 
$_SESSION["ErrMsg"] = ""; 
?> 

Put your html login form here 

main.php

<?php 
include("func.php"); 
if(EmptyStr($_SESSION["username"])){ //check if user has session (logged in) 
    $_SESSION["ErrMsg"] = "You need to logged in first to view this page!"; 
    redirect("/login.php"); 
} 
?> 
相關問題