Home >Backend Development >PHP Tutorial >Why Isn't My PHP Cookie Available Immediately After `setcookie()`?

Why Isn't My PHP Cookie Available Immediately After `setcookie()`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 09:21:111002browse

Why Isn't My PHP Cookie Available Immediately After `setcookie()`?

Accessing $_COOKIE Immediately After setcookie()

Problem: Why is $_COOKIE['uname'] not set immediately after calling the setcookie() function in PHP, even though it is set as expected upon the next execution of the script?

Answer: The cookie is not set until the response is sent back to the client and is not available in your PHP until a subsequent request.

However, you can set the cookie using setcookie() and then manually set the value in the $_COOKIE array:

setcookie('uname', $uname, time() + 60 * 30);
$_COOKIE['uname'] = $uname;

This will make the cookie value available immediately in your PHP script.

The above is the detailed content of Why Isn't My PHP Cookie Available Immediately After `setcookie()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn