无法弄清楚我对这个php条件做错了什么

时间:2015-07-16 02:10:19

标签: php html login credentials

我正在尝试使用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;
    }
?>

我已经成功完成了如果您的用户名/密码不正确(即不等于myusernameletmein),那么它会重定向到登录页面并回显一条错误消息形式。

我正在尝试这样做,以便当他们确认index.php上的表单时,表单消失并被替换为一些成功文本。但是,当我输入myusername和letmein时,它只是重定向到登录而没有错误,表单仍然显示。

从我已经完成的研究中,我需要使用if-else php结构,如我的index.php文件中所示,如果我想在我的php节点之间使用html,但我这样做是错误的吗?

谁能告诉我这里做错了什么?

3 个答案:

答案 0 :(得分:2)

如果您要使用会话来存储数据,请确保在您调用的每个页面的顶部都有session_start();。否则它不会读入会话标识符,并假设你想开始一个新标识符。

因此,在index.phpverifyCredentials.php的顶部添加命令。但请确保将其作为页面上的第一行代码。然后,您需要将其添加到任何直接请求的页面。

例如,如果您有index.php并且其中包含form.phpnav.php,则只有index.php需要session_start(),但如果您有form_processing.php链接至form_processing.php,然后session_start()也需要session_start()

答案 1 :(得分:2)

PHP Sessions要求您在使用$_SESSION的每个页面的顶部调用if ($this->form_validation->run() == FALSE) { $this->load->view('valform'); } else { $this->load->view('formsubmit'); } 。我不会在你的例子中看到它。

答案 2 :(得分:2)

噢,你接受了,因为我准备好了。 :(

以下是您需要使用的内容。无论如何.. (另外,你应该使用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

    }

    ?>
  

使用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;