This article mainly introduces the session and cookie usage of Symfony2, and summarizes and analyzes the implementation methods of the Symfony framework for session and cookie setting, obtaining, and deleting operations based on the instance form, for more information about the session and cookie usage of Symfony2, see the example in this article. We will share this with you for your reference. The details are as follows:
Session operation:
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 (); // clear session $ session-> clear ();}
Cookie operation:
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 (); // includes 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. the twig template calls the cookie:
{{ app.request.cookies.get('cookie_name') }}
I hope this article will help you design PHP programs based on the Symfony framework.