How to work with cookies?

html
<form id="test">
...
</form>
<div id="test2"></div>
the <script>
 $('#test').on('submit', function () {
 var params = $(this).serialize();

$.ajax({
 type: "POST",
 url: "index.php",
 data: params,
 headers: {
 'Cookie': document.cookie
}
})
 .done(function(msg) {
$('#test2').html(msg);
});
 return false;
});
</script>

index.php
<?php setcookie ('test', '1', time() + 60*60*24);
 echo $_COOKIE['test'];</code-->
<br / > Why ajax returns a cookie only for second times(i.e., the cookies delayed by 1 ajax request)?<br> I.e. in this case the first time you submit the ajax returns "Notice: Undefined index: test in ... ", and the second send will return "1". <br / > Can't understand, like first, set cookie <code>setcookie</code> then display it<br><code>echo $_COOKIE</code>. I can not understand how to fix it.
June 14th 19 at 18:01
1 answer
June 14th 19 at 18:03
Solution
Because cookies are installed by means of sending the response headers. Headers are sent before you print something (using echo, for example). $_COOKIE, in turn, is populated upon receipt of the request headers. That is, before code execution. Thus, it appears that this array during execution of the script the first time empty.

It turns out such a scheme:

The first execution of the script:
1) Come the request headers (Cookies available)
2) cookies are missing -> the $_COOKIE array is empty
3) Set cookies (the $_COOKIE array is still empty)
4) Send the response headers (array $_COOKIE is empty), set cookies on the client

The second execution of the script:
1) Come the request headers -> they already have a cookie.
2) $_COOKIE now contain what we established during the execution of the previous script.
...
and how it fixes? make baskets to the Internet via cookies - jaylon_Hahn74 commented on June 14th 19 at 18:06
Write an algorithm that will in addition to setting the cookie to remember them in a local array. Move this functionality into a separate class. Will use it something like this:
$storage = CookieStorage($_COOKIE);
$storage->set('test_key', 'value');
$storage->get('test_key');
- Manuela.Ho commented on June 14th 19 at 18:09
thank you! And do not tell me, then that's another issue arose when processing the rows of cookies.
There is a variable $id,
is the string $str.
I don't know how to write the condition
if ($str matches the pattern $id.":".any number) {
...
}

can tell me?) - jaylon_Hahn74 commented on June 14th 19 at 18:12
regular expression to help you. - Manuela.Ho commented on June 14th 19 at 18:15
, $pattern ="/".$id.":[0-9]+/u" turns? - jaylon_Hahn74 commented on June 14th 19 at 18:18
Yes. For the future, go to 101regex and test of the regular season. Quick and easy. - Manuela.Ho commented on June 14th 19 at 18:21

Find more questions by tags PHP