2016-05-15 160 views
0

因此,我建立了我的第一個使用註冊和登錄的網站,並使用php和mysql實施。我的問題是,如果用戶獲得了他在通過登錄頁面後訪問的頁面的URL,他目前能夠將這些頁面複製並粘貼到URL中並繞過登錄。登錄並繞過登錄屏幕

問題:有什麼辦法可以確保實際登錄發生?

我的主機000Webhost(免費)允許文件夾被密碼保護,但我不知道如何或如果我可以將此綁定到我的用戶數據庫。

這是我在這個問題上提出的第一個問題..請客氣一點。

+0

發佈此她:http://stackoverflow.com/questions/37234576/php-setting-the-session-information-in-a-cookie-wont-be-after-page-reload – Munsterlander

+0

@Paul對我的回答有幫助嗎? – Webeng

回答

1

是的,有一些簡單的方法可以檢查用戶是否登錄,最好的方法是使用超全球性的$_SESSION。當你使用session superglobal時,你基本上是將信息保存到服務器上,並且保存特定用戶的信息,同時在用戶計算機上保存一個cookie,只要會話有效(通常是30分鐘) 。用簡單的英語,php開發人員製作了一個超全球化的版本,基本上使開發人員可以非常容易地「維護狀態」,而無需執行極端數量的代碼。

這就是你將如何使用session superglobal。在您的網站的每一個頁面的頂部,你將有代碼(甚至高於<!DOCTYPE html>)此部分:

<?php session_start(); ?> 

這樣做(很多其他事情中)有什麼節省用戶計算機上的cookie識別他在會議有效期間獨一無二。 現在...用戶已經登錄後進入的頁面上,你將有類似下面的代碼:

<?php 

$username = $_POST['username'];//obtaining username from form 
$password = $_POST['password'];//obtaining password from form 
// i did not include any encryption code in this example 
// so that the example is easier to understand, but keep in mind 
// that encrypting your users passwords is super important 

//for security reasons, I used prepared statements and binding parameters 
//to compare the password and username obtained from the form with 
//those in the database (in order to prevent sql injection): 
$sql = "SELECT 1 FROM users WHERE username = :username AND password = :password LIMIT 1"; 
$stmt = $conn->prepare($sql); 
$stmt->bindParam(':username', $username); 
$stmt->bindParam(':password', $password); 
$stmt->execute(); 

if ($stmt->rowCount()>0)//if a row was found, then you know this user exists 
{ 
//here I am saving information in the session super global that 
//can be used to not only identify if a user is logged in on each 
//page, but also to see which user is logged in, since often 
//you want to give a user his own control panel or other features. 
    $_SESSION['authenticated'] = TRUE; 
    $_SESSION['username'] = htmlspecialchars($username); 
} 

?> 

現在每一個頁面,你有,你將包括下列代碼上:

<?php 
if (isset($_SESSION['authenticated'])) 
{ 
    echo "Hello there ".$_SESSION['username']."!<br>"; 
} 
?> 

之前的代碼會回顯「Hello there John!」之類的東西。如果用戶名是John。從這裏,你可以在你想要的內容中包含你想要的內容的任何代碼,只需要用戶登錄就可以看到因此,沒有登錄的用戶將無法查看該網站的哪一部分,即使他們會看到這些網站徽標以及其他不在條件內的其他所有內容。此外,以前的代碼不一定非要在最上面,只需要<?php session_start(); ?>,這是由於HTTP協議工作原因。

讓我知道這是否有幫助,或者如果您有任何其他問題。

+0

好吧,我也試過這個,並且得到以下錯誤:致命錯誤:調用第14行第14行中的/home/a4049291/public_html/frontpage.html中的非對象的成員函數prepare()是 - $ stmt = $ connection-> prepare($ sql);新手是否有課程? – Paul

0

Webeng上面的答案有你需要的大部分內容,但是你需要看看你是如何建立數據庫連接的,這樣你才能正確地使用你準備好的語句。查找PDO或mysqli數據庫連接。

他完全正確地使用SESSION變量來跟蹤用戶是否已登錄,以及有關使用SQL的預準備語句。

我會改變他答案的一件事是每頁的頂部。我反而利用這一點,因此,如果用戶沒有在頁面加載時,他們被送回登錄頁面登錄:

if (!isset($_SESSION['username'])) { header("Location: login.php"); }