无法弄清楚我在这个 php 条件下做错了什么
Can't figure out what I'm doing wrong with this php conditional
我正在尝试使用 php 做一个非常简单的登录系统。我现在有两个文件:index.php 和 verifyCredentials.php
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Site</title>
</head>
<body>
<h1>Welcome to My Test Homepage!</h1>
<?php if ($_SESSION['logged_in'] != "true") : ?>
<form method="post" action="verifyCredentials.php">
Username: <input type="text" name="username" value=""/><br>
Password: <input type="password" name="password" value=""/><br>
<input type="submit" name="submit" value="Submit"/><br>
</form>
<?php else : ?>
<h2>You're logged in! :)</h2>
<?php endif ?>
<?php if($_GET['verferr']==1){echo "<b>Login failed: incorrect username or password.</b>";} ?>
</body>
</html>
verifyCredentials.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "myusername" && $password == "letmein")
{
$_SESSION['logged_in'] = "true";
header("Location: index.php");
exit;
}
else
{
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
?>
我已经成功做到了,如果你的 username/password 不正确(即不等于 myusername
和 letmein
),那么它会重定向到登录页面并回显表格下的错误信息。
我正在尝试做到这一点,以便当他们确实验证 index.php 上的表单时,该表单会消失并被一些成功文本所取代。但是,当我输入 myusername 和 letmein 时,它只是重定向到登录而没有错误,并且表单仍然显示。
根据我所做的研究,如果我想在 html 中使用 index.php 文件中所示的 if-else php 结构在我的 php 个节点之间,但我做错了吗?
谁能告诉我这里做错了什么?
如果您打算使用会话来存储数据,请确保您调用的每个页面的顶部都有 session_start();
。否则它不会读入会话标识符,并假定您要开始一个新的会话标识符。
所以在 index.php
和 verifyCredentials.php
的顶部添加命令。但请确保将其作为页面上的第一行代码。然后,您需要将其添加到直接请求的任何页面。
例如,如果您有 index.php
,它包括 form.php
和 nav.php
,那么只有 index.php
需要 session_start()
,但是如果您有 link 到 form_processing.php
,那么 form_processing.php
也需要有 session_start()
。
PHP Sessions 要求您在使用 $_SESSION
的每个页面顶部调用 session_start()
。我在你的例子中没有看到它。
噢,我已经准备好了,你就接受了。 :(
这是您需要使用的。反正..
(此外,您应该使用 jQuery 以获得更好的过渡效果,请参见下文)
<?php
session_start();
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
$username = $post['username'];
$password = $post['password'];
if($username == "myusername" && $password == "letmein") {
$_SESSION['logged_in'] = true;
header("Location: index.php");
exit;
} else {
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
}
if ($_SESSION['logged_in'] === true) {
//User has logged in
}
?>
Using jQuery
HTML
<div id="loginForm">
<form id="myLoginForm">
<input id="username">
<input id="password">
<button id="formSubmit" name="formSubmit">Submit Form</button>
<input style="display: none;" type="text" id="realSubmit" name="realSubmit" value="hidden">
</form>
</div>
<div id="successPage">
Thank you for loggging in...
</div>
<div id="loginHome">
Login Homepage
Welcome <span id="displayUsername"></span>
</div>
jQuery
(function($){
$(function(){
$("#formSubmit").on('click', function() {
var username= $("#username").val();
var password = $("#password").val();
var data = {username: username, password: password};
delegateAjax('../myAjax.php', data, 'POST');
});
});
function delegateAjax(url, data, responseType, dataType, callback) {
function successHandler(data) {
console.log("Ajax Success");
var responseData = $.parseJSON(data);
if (responseData.status === 'Success') {
$("#loginForm").fadeOut(1500, function() {
$("#successPage").fadeIn(1500, function() {
$(this).fadeOut(1500, function() {
$("#displayUsername").html(responseData.username);
$("#loginHome").fadeIn(1500);
});
});
});
}
};
function failureHandler(xhr, status, error) {
console.log("Ajax Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler404(xhr, status, error) {
console.log("404 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler500(xhr, status, error) {
console.log("500 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
data = typeof data !== 'undefined' ? data : new Object();
responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
dataType = typeof dataType !== 'undefined' ? dataType : 'json';
callback = typeof callback !== 'undefined' ? callback : 'callback';
var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback,
statusCode: { 404: handler404, 500: handler500 }});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
};
})(jQuery);
PHP
myAjax.php
<?php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if (!IS_AJAX) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
$pos = strpos($_SERVER['HTTP_REFERER'], getenv('HTTP_HOST'));
if ($pos === false) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
function validUser($data) {
//connect to db and validate user
$dbi = new mysqliObject();
$params['string'] = $data['username'];
$dbi->newSelect($params);
$table = 'users';
$select = '*';
$where = '`username` = ? LIMIT 1';
if ($dbi->exec($table, $select, $where)) {
$result = $dbi->result[0];
return passwordVerify($result['password']); //true/false
} else {
//for debugging
//echo 'Last Error: '.$dbi->get('lastError').'<br>'."\r\n";
//echo 'Last Query: '.$dbi->get('lastQuery').'<br>'."\r\n";
return false;
}
}
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
if (validUser($post)) {
$response['status'] = 'success';
$response['username'] = $username;
echo json_encode($response);
exit;
} else {
$response['status'] = 'Failed';
$response['message'] = 'Username/Password Invalid';
echo json_encode($response);
exit;
}
}
$response['status'] = 'Error';
$response['message'] = 'POST Data Invalid';
echo json_encode($response);
exit;
我正在尝试使用 php 做一个非常简单的登录系统。我现在有两个文件:index.php 和 verifyCredentials.php
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Site</title>
</head>
<body>
<h1>Welcome to My Test Homepage!</h1>
<?php if ($_SESSION['logged_in'] != "true") : ?>
<form method="post" action="verifyCredentials.php">
Username: <input type="text" name="username" value=""/><br>
Password: <input type="password" name="password" value=""/><br>
<input type="submit" name="submit" value="Submit"/><br>
</form>
<?php else : ?>
<h2>You're logged in! :)</h2>
<?php endif ?>
<?php if($_GET['verferr']==1){echo "<b>Login failed: incorrect username or password.</b>";} ?>
</body>
</html>
verifyCredentials.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "myusername" && $password == "letmein")
{
$_SESSION['logged_in'] = "true";
header("Location: index.php");
exit;
}
else
{
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
?>
我已经成功做到了,如果你的 username/password 不正确(即不等于 myusername
和 letmein
),那么它会重定向到登录页面并回显表格下的错误信息。
我正在尝试做到这一点,以便当他们确实验证 index.php 上的表单时,该表单会消失并被一些成功文本所取代。但是,当我输入 myusername 和 letmein 时,它只是重定向到登录而没有错误,并且表单仍然显示。
根据我所做的研究,如果我想在 html 中使用 index.php 文件中所示的 if-else php 结构在我的 php 个节点之间,但我做错了吗?
谁能告诉我这里做错了什么?
如果您打算使用会话来存储数据,请确保您调用的每个页面的顶部都有 session_start();
。否则它不会读入会话标识符,并假定您要开始一个新的会话标识符。
所以在 index.php
和 verifyCredentials.php
的顶部添加命令。但请确保将其作为页面上的第一行代码。然后,您需要将其添加到直接请求的任何页面。
例如,如果您有 index.php
,它包括 form.php
和 nav.php
,那么只有 index.php
需要 session_start()
,但是如果您有 link 到 form_processing.php
,那么 form_processing.php
也需要有 session_start()
。
PHP Sessions 要求您在使用 $_SESSION
的每个页面顶部调用 session_start()
。我在你的例子中没有看到它。
噢,我已经准备好了,你就接受了。 :(
这是您需要使用的。反正.. (此外,您应该使用 jQuery 以获得更好的过渡效果,请参见下文)
<?php
session_start();
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
$username = $post['username'];
$password = $post['password'];
if($username == "myusername" && $password == "letmein") {
$_SESSION['logged_in'] = true;
header("Location: index.php");
exit;
} else {
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
}
if ($_SESSION['logged_in'] === true) {
//User has logged in
}
?>
Using jQuery
HTML
<div id="loginForm">
<form id="myLoginForm">
<input id="username">
<input id="password">
<button id="formSubmit" name="formSubmit">Submit Form</button>
<input style="display: none;" type="text" id="realSubmit" name="realSubmit" value="hidden">
</form>
</div>
<div id="successPage">
Thank you for loggging in...
</div>
<div id="loginHome">
Login Homepage
Welcome <span id="displayUsername"></span>
</div>
jQuery
(function($){
$(function(){
$("#formSubmit").on('click', function() {
var username= $("#username").val();
var password = $("#password").val();
var data = {username: username, password: password};
delegateAjax('../myAjax.php', data, 'POST');
});
});
function delegateAjax(url, data, responseType, dataType, callback) {
function successHandler(data) {
console.log("Ajax Success");
var responseData = $.parseJSON(data);
if (responseData.status === 'Success') {
$("#loginForm").fadeOut(1500, function() {
$("#successPage").fadeIn(1500, function() {
$(this).fadeOut(1500, function() {
$("#displayUsername").html(responseData.username);
$("#loginHome").fadeIn(1500);
});
});
});
}
};
function failureHandler(xhr, status, error) {
console.log("Ajax Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler404(xhr, status, error) {
console.log("404 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler500(xhr, status, error) {
console.log("500 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
data = typeof data !== 'undefined' ? data : new Object();
responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
dataType = typeof dataType !== 'undefined' ? dataType : 'json';
callback = typeof callback !== 'undefined' ? callback : 'callback';
var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback,
statusCode: { 404: handler404, 500: handler500 }});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
};
})(jQuery);
PHP
myAjax.php
<?php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if (!IS_AJAX) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
$pos = strpos($_SERVER['HTTP_REFERER'], getenv('HTTP_HOST'));
if ($pos === false) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
function validUser($data) {
//connect to db and validate user
$dbi = new mysqliObject();
$params['string'] = $data['username'];
$dbi->newSelect($params);
$table = 'users';
$select = '*';
$where = '`username` = ? LIMIT 1';
if ($dbi->exec($table, $select, $where)) {
$result = $dbi->result[0];
return passwordVerify($result['password']); //true/false
} else {
//for debugging
//echo 'Last Error: '.$dbi->get('lastError').'<br>'."\r\n";
//echo 'Last Query: '.$dbi->get('lastQuery').'<br>'."\r\n";
return false;
}
}
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
if (validUser($post)) {
$response['status'] = 'success';
$response['username'] = $username;
echo json_encode($response);
exit;
} else {
$response['status'] = 'Failed';
$response['message'] = 'Username/Password Invalid';
echo json_encode($response);
exit;
}
}
$response['status'] = 'Error';
$response['message'] = 'POST Data Invalid';
echo json_encode($response);
exit;