English 中文(简体)
检查是否有 PHP cookie 存在, 如果不设置其值
原标题:Check if a PHP cookie exists and if not set its value

我在多语种网站工作,

echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
    setcookie("lg", "ro");
echo $_COOKIE["lg"];

如果客户端没有 lg cookie (因此,这是他们第一次访问该网站), 则为该用户设置 cookie lg = ro

一切正常, 只是如果我第一次输入此页面, 第一和第二个 echo 将不返回任何信息。 只有我刷新页面是饼干组, 然后两个 echo 都会打印“ ro” 字符串 。

如何设置此 cookie 来从第二个 < code>> echo 上查看其值? 不需要更新页面或创建重定向 。

最佳回答
问题回答

如果您用php setcookie 设置一个 cookie,那么 就能看到 cookie 的集和值 , 举例来说, 使用 Firefox 开发工具 仅以时间 为例。

但你需要重新装入/装入 同一/ 下一个 page ,如果你想阅读、获取或检查 cookie 和 内值,才能与 PHP 中的 cookie 一起工作。

在此示例中, 如果您想要 reload , 您可以使用 > HTML JAVASCRIPT , 以 > PHP HTML JAVASCRIPT 的同页 < /code>,

如果不接受 cookie 或禁用 cookie, 将获得一个装入环, 浏览器将停止装入该页面 。

< pHP 头版 Reload Same PAGE / penger > 的长方程 :

<?php

$COOKIE_SET     = [
      expires   =>  0 
    , path      =>  / 
//  , domain    =>  DOMAIN 
    , secure    =>  true 
    , httponly  =>  true 
//  , samesite  =>  Strict 
    ];
    
$COOKIE_NAME    = "MYCOOKIE";
$COOKIE_VALUE   = "STACKOVERFLOW";
    
if(!isset($_COOKIE[$COOKIE_NAME])){
    setcookie($COOKIE_NAME, $COOKIE_VALUE, $COOKIE_SET);
    // YOU NEED TO RELOAD THE PAGE ONCE
    // WITH PHP, HTML, OR JAVASCRIPT
    // UNCOMMENT YOUR CHOICE
    
    // echo  <meta http-equiv="refresh" content="0;URL=/"> ;
    // echo  <script>window.location.replace("/");</script> ;
    header("Location: /");
    exit;
  }
else{
    echo ($_COOKIE[$COOKIE_NAME]);
}
  
?> 

带有PHP头版RELAD Same PAGE /强:

if(!isset($_COOKIE[ MYCOOKIE ])){
    setcookie( MYCOOKIE ,  STACKOVERFLOW );
    header("Location: /");
    exit;
}

echo ($_COOKIE[ MYCOOKIE ]);




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...