我想建立一個簡單的用戶授權系統,其中.txt文件存儲用戶名和密碼信息。我知道這可能應該以不同的方式完成(通過數據庫),但我正在做這個練習。如果任何人都可以幫我解決我的問題,將不勝感激。關於用戶授權在PHP的問題
到目前爲止,我已經建立了register.php和login.php,但我不確定從這裏去哪裏。這裏是我的三個問題:
假設我有一個我希望保護的html網站。我將如何合併login.php,以便如果未登錄的用戶嘗試訪問頁面的內容,系統會提示他們登錄?我需要在每個html頁面中放置什麼東西嗎?
如何在此過程中實施Cookie?登錄的用戶在20分鐘內不必重新登錄。理想情況下,我想在用戶登錄後發送cookie,但我該怎麼做?
我想我的register.php檢查現有的用戶,所以所有的名字都是唯一的。到目前爲止,我沒有正確地做到這一點。我的代碼有什麼問題?
這裏是我的代碼:
的login.php
<?php
$check = 0;
if (isset($_POST['submit']))
{
$name = htmlentities($_POST['name']);
$name = strtolower($name);
$password = htmlentities($_POST['apw']);
$filename = getcwd() . "/psverification.txt";
$lines = file($filename , FILE_IGNORE_NEW_LINES);
printf ("Hi %s,</br />", $name);
foreach($lines as $key => $line)
{
list($username, $pw) = explode('|', $line);
if($username == $name && $pw == $password)
$check++;
break;
}
if ($check == 1){
//Redirect to home page
Header("Location: index.html");
}
else{
printf("Your username or password are invalid. Please try again.");
}
}
?>
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
Username:<br />
<input type = "text" id="name" name="name" size="20" maxlength="40" />
</p>
<p>
E-mail Address:<br />
<input type = "text" id="apw" name="apw" size="20" maxlength="40" />
</p>
<input type="submit" id="submit" name ="submit" name ="submit" value="Log in" />
<p>
<a href="register.php">Register</a></p>
</form>
REGISTER.PHP
<?php
if (isset($_POST['submit']))
{
$username = $_POST['user'];
$password = $_POST['password'];
$confirmpw = $_POST['confirmpw'];
$username = strtolower($username);
//Check if passwords match
if ($password != $confirmpw){
print "Passwords do not match, please try again.";
}
else{
//the data
$data = "$username|$password\n";
//open the file and choose the mode
$fh = fopen("psverification.txt", "a+");
// Cycle through the array
while (($buffer = fgets($fh, 4096)) !== false)
{
// Parse the line
list($usercheck, $passwordcheck) = explode('|', $buffer);
if (trim($usercheck) == $username)
{
print "The username is already in our system. Please use another one.";}
else {
fwrite($fh, $data);
//Redirect to home page
Header("Location: index.html");
}
}
//close the file
fclose($fh);
}
}
?>
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
Username:<br />
<input type = "text" id="user" name="user" size="20" maxlength="40" />
</p>
<p>
Password:<br />
<input type = "password" id="password" name="password" size="20" maxlength="40" />
</p>
Confirm Password:<br />
<input type = "password" id="confirmpw" name="confirmpw" size="20" maxlength="40" />
</p>
<input type="submit" id="submit" name ="submit" name ="submit" value="Register" />
</form>
在此先感謝。任何例子將不勝感激。
你或許應該打破這種成獨立的問題。至少#3部分,因爲它不是概念,但你的實際代碼。 – mrtsherman
同意。單獨的,更具體的問題會更合適。 – DesignerGuy
@all我很感謝你的回答。我希望我可以將每個人的回答標記爲「接受」......他們都幫助我很多。 – Moses89