Sending and reading cookies in Yii_php example

WBOY
Release: 2016-08-17 13:02:41
Original
825 people have browsed it

cookies:

  //The newly created cookie will be transferred from the local to the server, and then obtained from the server.

(1) Sending of cookies

 $cookies = Yii::$app->response->cookies;
   // 在要发送的响应中添加一个新的cookie
  eg:往cookies中添加用户名和密码
  $cookies->add(new Cookie(['name'=>'username', 'value'=>$username,]));
  $cookies->add(new Cookie(['name'=>'password', 'value'=>$password,]));
  //删除一个cookie
  $cookies->remove('username');
  //相当于
  unset($cookies['username']);
Copy after login

(2) Cookie acquisition

$cookies = Yii::$app->request->cookies;
  // 获取名为 "username" cookie 的值,如果不存在,返回默认值"en" 
  $username = $cookies->getValue('username', 'en');
  // 另一种方式获取名为 "username" cookie 的值
  if (($cookie = $cookies->getValue('username')) !== null) {
    $username = $cookie->value;
  }
// 判断是否存在名为username的cookie
if (isset($cookies['username'])) {
$username= $cookies['username']->value;  ...
}if($cookies->has('username')){}
Copy after login

The above is what the editor introduces to you about sending and reading cookies in Yii. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the Script House website!

Related labels:
yii
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template