Home  >  Article  >  Backend Development  >  Check if PHP cookie exists and set its value if not

Check if PHP cookie exists and set its value if not

WBOY
WBOYforward
2023-08-20 23:18:501411browse

检查PHP cookie是否存在,如果不存在则设置其值

According to the PHP manual, the existence of the cookie cannot be found.

A reference in the manual: "Once cookies are set, they can be accessed on the next page load using the $_COOKIE or $HTTP_COOKIE_VARS array."

The reason is that cookies are sent to the browser as response headers, and the browser needs to send them back in the next request. That's why they are only available on the second page load.

But here is a solution: you can set $_COOKIE-

if(!isset($_COOKIE['lg'])) {
   setcookie('lg', 'ro');
   $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
when calling the setcookie function

The above is the detailed content of Check if PHP cookie exists and set its value if not. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete