php cookie does not work at the first time reading

前端 未结 3 1122
有刺的猬
有刺的猬 2020-12-12 06:18

I am a beginner for PHP and studying to use cookie for login. Would any body please check my code to see what is my problem, or let me how to fix this problem.

Wh

相关标签:
3条回答
  • 2020-12-12 06:52

    As a workaround you could use location() after checking the cookie to have access to the stored data.

    But be aware that location() fails, if anything (including breaks and blanks in your script) already sent to the browser.

    0 讨论(0)
  • 2020-12-12 07:05

    Give zerkms the answer, but I just want to reiterate:

    1. Cookies are not bad for storing bits of info like the user's theme preferences or preferred start page, etc. They get their bad rep from being used for identity and authentication handling. There are cookies out there that basically have "isAdmin=0" in order to control user access. It is very easy to change that to isAdmin=1 and have a field day. Since you are new to PHP, take the time to learn about sessions now while it's all new to you.

    2. When you set a cookie using setcookie, you are sending an HTTP header to the browser with the cookie info. The browser will then pass back that cookie in any future requests to the server. The $_COOKIE global variable holds the cookie info passed in from the browser to the server.

    3. Since you are using $_REQUEST to get the cookie name, you don't need to check the cookie (otherwise you wouldn't have the data to set it right?). So consider going this route:

      if(!isset($_COOKIE['cookiename'])) {
            $name = $_POST['name']);
            setcookie("cookiename",$name);
       } else {
          $name = $_COOKIE['cookiename']);
       }
      
      echo "Welcome back $name!";
      

    This will also help out if they clear cookies, etc.

    But really, the safer route is:

    session_start();
    if(!isset($_SESSION['name'])){
        $_SESSION['name'] = $_POST['name']);
    }
    if(!isset($_SESSION['pwd'])){
        $_SESSION['pwd'] = $_POST['pwd']);
    }
    
    $name =  $_SESSION['name'];
    $pwd = $_SESSION['pwd'];
    

    And even this would be frowned upon for serious web security, where you should simply check the password against a stored hash and then delete it, using other global variables to confirm session integrity. But there's now a whole StackExchange for that.

    0 讨论(0)
  • 2020-12-12 07:12

    setcookie only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE superglobal.

    In other hand - $_COOKIE is filled up with the cookies sent from the client

    So at first step - you set the cookie with setcookie and have nothing in $_COOKIE because client hasn't sent it yet, and will only on the next request.

    And there is no way of doing what you want, rather than modifying $_COOKIE manually

    PS: it is a bad idea to put user's password in the cookie

    0 讨论(0)
提交回复
热议问题