How to set a cookie with php and symfony?

by ryan.murray , in category: PHP Frameworks , 10 months ago

How to set a cookie with php and symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 10 months ago

@ryan.murray 

To set a cookie with PHP and Symfony, you can use the Response object provided by Symfony. Here is an example of how to set a cookie in Symfony:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationCookie;

// Create a new Response object
$response = new Response();

// Create a new Cookie instance
$cookie = new Cookie('cookie_name', 'cookie_value', time() + 3600);

// Add the cookie to the response
$response->headers->setCookie($cookie);

// Send the response back to the user
$response->send();


In this example, we create a new Response object and a Cookie instance. The Cookie constructor takes three arguments: the cookie name, the cookie value, and the expiration time (in this case, one hour from the current time). We then add the cookie to the response using the setCookie() method of the headers property of the response object.


Finally, we send the response back to the user using the send() method. The user's browser will receive the response with the cookie set, and subsequent requests to your Symfony application will include the cookie in the request headers.