我为 PHP 注册和登录创建了一个演示,并且测试良好。
这是 reg html:
<html>
<head>
<title> Reg Page </title>
</head>
<body>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td> UserName</td>
<td> <input type="text" name="user" > </td>
</tr>
<tr>
<td> PassWord </td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> <input type="submit" name="reg" value="REG"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
注册php如下:
<?php
if(isset($_POST["user"]) && isset($_POST["pass"]))
{
// check if user exist.
$file=fopen("data.txt","r");
$finduser = false;
while(!feof($file))
{
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['user'])
{
$finduser=true;
break;
}
}
fclose($file);
// register user or pop up message
if( $finduser )
{
echo $_POST["user"];
echo ' existed!\r\n';
include 'reg.html';
}
else
{
$file = fopen("data.txt", "a");
fputs($file,$_POST["user"].";".$_POST["pass"]."\r\n");
fclose($file);
echo $_POST["user"];
echo " registered successfully!";
}
}
else
{
include 'reg.html';
}
?>
登录表格:
<html>
<head>
<title> Login Page </title>
</head>
<body>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td> UserName</td>
<td> <input type="text" name="user" > </td>
</tr>
<tr>
<td> PassWord </td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> <input type="submit" name="login" value="LOGIN"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
登录php:
<?php session_start(); ?> // session starts with the help of this function
<?php
if(isset($_SESSION['use'])) // Checking whether the session is already there or not if
// true then header redirect it to the home page directly
{
header("Location:home.php");
}
else
{
include 'login.html';
}
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if(isset($_POST["user"]) && isset($_POST["pass"])){
$file = fopen('data.txt', 'r');
$good=false;
while(!feof($file)){
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['user'] && trim($array[1]) == $_POST['pass']){
$good=true;
break;
}
}
if($good){
$_SESSION['use'] = $user;
echo '<script type="text/javascript"> window.open("home.php","_self");</script>';
}else{
echo "invalid UserName or Password";
}
fclose($file);
}
else{
include 'login.html';
}
}
?>
我把源代码放在这里供参考。