创建一个简单的基于 PHP 和 MYSQL 的登录系统
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17067751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating A Simple PHP and MYSQL Based Login System
提问by ewizard
I am following along with the tutorial here:
我正在关注这里的教程:
https://www.dropbox.com/s/lta1r9xhk2u2ef0/3592029.doc
https://www.dropbox.com/s/lta1r9xhk2u2ef0/3592029.doc
I am basically using all the code from the tutorial. My problem is, there is no redirect after I log in - it just stays on the login page. I created a user in a mysql database with username "admin" and a password. I believe I am typing them in correctly - here is my code:
我基本上使用了教程中的所有代码。我的问题是,登录后没有重定向 - 它只是停留在登录页面上。我在 mysql 数据库中创建了一个用户名“admin”和一个密码的用户。我相信我输入正确 - 这是我的代码:
login.inc.php
登录.inc.php
<?php
//?Include?required?MySQL?configuration?file?and?functions
require_once('config.inc.php');
require_once('functions.inc.php');
//?Start?session
session_start();
//?Check?if?user?is?already?logged?in
if?($_SESSION['logged_in']?==?true)?{
//?If?user?is?already?logged?in,?redirect?to?main?page
redirect('../index.php');
}?
else?{
//?Make?sure?that?user?submitted?a?username/password?and?username?only?consists?of?alphanumeric?chars
if?(?(!isset($_POST['username']))?||?(!isset($_POST['password']))?OR (!ctype_alnum($_POST['username']))?)?{
redirect('../login.php');
}
//?Connect?to?database
$mysqli?=?@new?mysqli(DB_HOSTNAME,?DB_USERNAME,?
DB_PASSWORD,?DB_DATABASE);
//?Check?connection
if?(mysqli_connect_errno())?{
printf("Unable?to?connect?to?database:?%s",?
mysqli_connect_error());
exit();
}
//?Escape?any?unsafe?characters?before?querying?database
>real_escape_string($_POST['username']);
>real_escape_string($_POST['password']);
$sql?=?"SELECT?*?FROM?users?WHERE?username =?'"?.?$username?.?"'?AND?password?=?'"?.?md5($password)?.?"'";
$result?=?$mysqli->query($sql);
//?If?one?row?is?returned,?username?and?password?are valid
if?(is_object($result)?&&?$result->num_rows?==?1)?{
//?Set?session?variable?for?login?status?to?true
$_SESSION['logged_in']?=?true;
redirect('../index.php');
}
else {
//?If?number?of?rows?returned?is?not?one, redirect?back?to?login?screen
redirect('../login.php');
}
}
?>
login.php
登录.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta?http-equiv="Content-type"?content="text/html;charset=utf-8"?/>
<title>Creating?a?Simple?PHP?and?MySQL-Based?Login?System</title>
</head>
<body>
<form?id="login-form"?method="post"?action="includes/login.inc.php">
Username: <input type="text" name="username" id="username"><br>
Password: <input type="password" name="password" id="password"><br>
<input type="submit" id = "submit" name="Submit" value="Login">
</form>
</body>
</html>
The required helper files are:
所需的帮助文件是:
functions.inc.php:
函数.inc.php:
<?php
/**
*?Crucial?Functions?for?Application
*
*?@package?tpc_tutorials
*?@file????/includes/functions.inc.php
*
*?Redirects?to?specified?page
*
*?@param?string?$page?Page?to?redirect?user?to
*?@return?void
*/
function?redirect($page)?{
header('Location:?'?.?$page);
exit();
}
/**
*?Check?login?status
*
*?@return?boolean?Login?status
*/
function?check_login_status()?{
//?If?$_SESSION['logged_in']?is?set,?return?the?status
if?(isset($_SESSION['logged_in']))?{
return?$_SESSION['logged_in'];
}
return?false;
}
?>
config.inc.php
配置文件
<?php
/**
*?MySQL?Database?Configuration
*
*?@file?/includes/config.inc.php
*?@note?Replace?the?settings?below?with?those?for?your?MySQL?database.
*/
define('DB_HOSTNAME',?'localhost');
define('DB_USERNAME',?'root');
define('DB_PASSWORD',?'xxx');
define('DB_DATABASE',?'itit');
?>
I have tried switching out the "redirect()" function with the "header(...)" function with no luck.
我试过用“header(...)”函数切换“redirect()”函数,但没有成功。
UPDATE
更新
I'm getting this error:
我收到此错误:
Parse error: syntax error, unexpected T_STRING in /Users/Eamon/Sites/includes/login.inc.php on line 13
解析错误:语法错误,第 13 行 /Users/Eamon/Sites/includes/login.inc.php 中的意外 T_STRING
Does anyone see any syntax errors? (login.inc.php)
有没有人看到任何语法错误?(登录.inc.php)
<?php
error_reporting(E_ALL); ini_set('display_errors', '1');
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
}
else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ((!isset($_POST['username'])) || (!isset($_POST['password'])) OR (!ctype_alnum($_POST['username']))) {
redirect('../login.php');
}
// Connect to database
$mysqli = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s",
mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
real_escape_string($_POST['username']);
real_escape_string($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['logged_in'] = true;
redirect('http://localhost/~Eamon/index.php');
}
else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
回答by Rocket Hazmat
Your redirect
function is setting the Location
header. This does not work with relative paths.
您的redirect
功能正在设置Location
标题。这不适用于相对路径。
redirect('../index.php');
You can't do that. You need to use the absolute path to your page like:
你不能那样做。您需要使用页面的绝对路径,例如:
redirect('http://example.com/index.php');
回答by Damien Overeem
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['logged_in'] = true;
redirect('../index.php');
}
else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
If your query returns more then 1 row, it will redirect to the login.php. This also means that if your user exists twice in your database, you will only get redirected to the login page.
如果您的查询返回超过 1 行,它将重定向到 login.php。这也意味着如果您的用户在您的数据库中存在两次,您只会被重定向到登录页面。
Since your sql query does not limit the results, this might be the case.
由于您的 sql 查询不限制结果,因此可能是这种情况。
The best way for you to proceed is to find out where you end up in your code.
您继续的最佳方式是找出您在代码中的最终位置。
In example: change redirect('../index.php');
to die('redirect to ../index.php')
. and redirect('../login.php');
to die('redirect to ../login.php')
. Then execute your code and see what message you get. This will point you in the right direction.
例如:更改redirect('../index.php');
为die('redirect to ../index.php')
. 和redirect('../login.php');
到die('redirect to ../login.php')
。然后执行你的代码,看看你得到了什么消息。这将为您指明正确的方向。
Also make sure error reporting is on by adding error_reporting(E_ALL);
and ini_set('display_errors', 1);
to the top of your php page.
还要确保通过在 php 页面顶部添加error_reporting(E_ALL);
和ini_set('display_errors', 1);
来确保错误报告处于启用状态。
回答by syd619
Change your redirect function because I assume it is a path issue
更改重定向功能,因为我认为这是路径问题
function redirect($page) {
//assuming your page is smthing like welcome.php
header('Location: http://' . $_SERVER['SERVER_NAME'] . '/' . $page);
exit();
}
回答by tornados
Do the sessions work? Have you done some debugging? Is it reaching inside "if (is_object($result) && $result->num_rows == 1) " block? If its only the redirect problem then you just need to make sure that there are no blank spaces or any characters printed before you call redirect function. Otherwise if the problem is somewhere else, you'll have to find it out by debugging it on each step.
会议有效吗?你做了一些调试吗?它是否到达“if (is_object($result) && $result->num_rows == 1)”块内?如果它只是重定向问题,那么您只需要确保在调用重定向函数之前没有空格或任何打印的字符。否则,如果问题出在其他地方,则必须通过在每个步骤中进行调试来找出问题所在。