欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Symfony2之session与cookie用法小结

程序员文章站 2024-04-01 22:10:40
本文实例讲述了symfony2之session与cookie用法。分享给大家供大家参考,具体如下: session操作: 1. set session: pu...

本文实例讲述了symfony2之session与cookie用法。分享给大家供大家参考,具体如下:

session操作:

1. set session:

public function testsetsession() {
  $session = $this->getrequest()->getsession();
  $session->set($sessionname, $sessionvalue );
}

2. get session:

public function testgetsession() {
 $session = $this->getrequest()->getsession();
 $username = $session->get($sessionname);
}

3. clear session:

public function testclearsession() {
  $session = $this->getrequest()->getsession();//清除session
  $session->clear();
}

cookie操作:

1. set cookie

use symfony\component\httpfoundation\response;
use symfony\component\httpfoundation\cookie;
public function testsetcookie($name, $value, $expire=0){
 $response = new response();
 $response->headers->setcookie(new cookie($name, $value, time() + $expire));
 $response->send(); // 包括 sendheaders()、sendcontent()
}

2. get cookie:

public function testgetcookie() {
 $request = $this->getrequest();
 return $request->cookies->all();
}

3. clear cookie:

public function testclearcookie() {
 $response = new response();
 $response->headers->setcookie(new cookie($name, $value, -1));
 $response->send();
}

4. twig模板调用cookie:

{{ app.request.cookies.get('cookie_name') }}

希望本文所述对大家基于symfony框架的php程序设计有所帮助。