Help a Beginner with a PHP based Login System

纵饮孤独 提交于 2019-12-13 05:08:35

问题


I'm a bit embarrassed to say, but I've run into issue with creating a PHP based login system. I'm using a site template to handle the looks of the the login process, so I will spare you the code. Here is my thought process on how to handle the login:

Create a simple login.php file. On there will be a form whose action is set to itself. It will check to see if the submit has been clicked, and if so validate to make sure the user entered a valid password / username. If they do, set a session variable save some login info (username, NOT password), and redirect them to a restricted area. If the login info isn't valid, save an error message in a session variable, display error message giving further instruction, and wait for the user to resubmit. Here is a chunk of what I have - hopefully one of you experts can see where I've gone wrong, and give me some insight:

<?php
session_start();

if(isset($_POST['submit'])) {
    if(!empty($_POST['username']) AND !empty(!$_POST['password']))
    {
        header("Location: http://www.google.com");
    } else {
        $err = 'All the fields must be filled in!';
    }
}

if($err) {
    $_SESSION['msg']['login-err'] = $err;
}
?>

Now the above is just an example - the intent of the above code is to process user input, with the script validating simply that the user has given input for username and password. If they have, I would like them, in this case, to be redirected to google.com (for the sake of this example). If not, save an error message. Given my current code, the error message will display perfectly, however if the user submits and has something entered for the username and password, the page simply doesn't redirect. I'm sure this is a silly question, but I am a beginner, and well, to be honest, a bit buzzed right now. Thanks so much!


回答1:


Well, without looking at the rest of your code it's difficult to say. But with headers, the header must be sent before anything is written to the response stream (ie before any echo statements OR any code that is not included inside of <?php ... ?> tags) so that could be why it isn't redirecting. The code you supplied looks good to me.




回答2:


if(!empty($_POST['username']) AND !empty(!$_POST['password']))
                                         ^--- negating a string = pointless

That logic is highly ugly to read, you should redo it as:

if(empty($_POST['username']) OR empty($_POST['password'])) {
   die("Fill in both fields");
}


来源:https://stackoverflow.com/questions/2642494/help-a-beginner-with-a-php-based-login-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!