Help me please ! In PHP, after authorization, we have to display the login, I saved it in a cookie and then such an error.

PHP:

$login = $_POST["cooklog"]; 

setcookie("login", $login, time() + (3600*24)*30, "/");

$xlogin = $_COOKIE["login"];

echo json_encode($xlogin);

Js:

 xmlhttp.open("POST", "functions.php", true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send("cooklog=" + encodeURIComponent(login)); alert(response); 

    1 answer 1

    setcookie forms the HTTP header in the response to the browser. The $_COOKIE takes values ​​from the browser's request headers. Look carefully at how the HTTP protocol is arranged or any article about cookies and HTTP headers. Or just look in Wireshark for HTTP traffic of your code, everything is also very clear and clear there, if you know where to look

    Simply put, the $_COOKIE["login"] cookie at the time of accessing it has not yet been defined. To be precise, in the $_COOKIE array, $_COOKIE is still no "login" key, and a call to a non-existent element will cause an error

    Just check any value before using it:

     $login = $_POST["cooklog"]; setcookie("login", $login, time() + (3600*24)*30, "/"); $xlogin = isset($_COOKIE["login"]) ? $_COOKIE["login"] : NULL; if ($xlogin) { echo json_encode($xlogin); } else { // Напишите, что делать, если логика в куках нет } 

    By the way, $_POST["cooklog"] also advisable to check before use. In general, all calls to arrays need to be checked, you are trying to work with what may not be, and create yourself a lot of problems for the future

    • And just output response or response.login? - VIP300100
    • You have something strange written in js code, look at xmlhttprequest.ru/#use , specifically "Asynchronous XMLHttpRequest" - your response in js code is also not defined, and there is no AJAX response handler - wirtwelt
    • So I cut the code, there is a lot of things before that, and all that is asynchronous XMLHttpRequest - VIP300100
    • xmlhttp is a request object, it has an onreadystatechange function, it is called every time a request changes status (asynchronously). You need to find this function and look at the server response processing inside it. Immediately after send it makes no sense to output xmlhttp.responseText - it has not yet gone and has not returned) - wirtwelt
    • I do this, I cut the code, now it displays null - VIP300100