簡體   English   中英

無法找出我在用這個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;
    }
?>

我已經成功做到了,如果您的用戶名/密碼不正確(即不等於myusernameletmein ),那么它將重定向到登錄頁面,並在表單下顯示一條錯誤消息。

我正在嘗試這樣做,以便當他們確實驗證index.php上的表單時,該表單會消失並被一些成功文本替換。 但是,當我鍵入myusername和letmein時,它只是重定向到登錄名而沒有錯誤,並且表單仍然顯示。

根據我所做的研究,如果我想在php節點之間插入html,則必須使用index.php文件中所示的if-else php結構,但是這樣做是否錯誤?

有人可以告訴我我在做什么錯嗎?

如果要使用會話存儲數據,請確保您具有session_start(); 在您調用的每個頁面的頂部。 否則,它將不會讀入會話標識符,並會假定您要啟動一個新的會話標識符。

因此,在index.phpverifyCredentials.php的頂部添加命令。 但是請確保將其作為頁面上的第一行代碼。 然后,您需要將其添加到直接請求的任何頁面中。

例如,如果您具有index.php並且其中包括form.phpnav.php ,則僅index.php將需要session_start() ,但是如果您具有到form_processing.php的鏈接,則form_processing.php將需要也有session_start()

PHP會話要求您在使用$_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

    }

    ?>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM