sFire PHP Framework

Cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With sFire\Cookie\Cookie, you can both create and retrieve cookie values.

In this section we will handle:

  • Add cookies
  • Read cookies
  • Remove cookies
  • Encrypting cookies

Add cookies

Parameters
Cookie :: add(string $name, string $value, [int $seconds, boolean $encrypt, string $path, string $domain, boolean $secure, boolean $httponly]);
Example
Cookie :: add('foo', 'bar');
Cookie :: add('foo', 'bar', 60); //60 seconds

Read cookies

There are different ways to read cookies.

Get

To read the cookie value based on a string key, you may use the get method.

echo Cookie :: get('foo');

All

To retrieve all the cookies you can use the all method. This method will return an Array with all the cookies.

$cookies = Cookie :: all();
print_r($cookies);

Has

If you want to check if a cookie exists, you can use the has method. This method will return a boolean true if exists and a Boolean false if not.

$exists = Cookie :: has('foo');
var_dump($exists); //Outputs true/false

You may also use the pull method to read the cookie (see the pull method in the removing cookies section for more details).

Removing cookies

You can delete a single cookie, pull a single cookie or even flush them all.

Remove a single cookie

To delete a cookie you may use the remove method. This method deletes the cookie based on a String key.

Cookie :: remove('foo');

Pull a single cookies

The pull method lets you read and delete the cookie for single use.

echo Cookie :: pull('foo'); //Will output the value of the cookie "foo" and removes it after

Remove all cookies

To delete all cookies you may use the flush method.

Cookie :: flush();

Encrypting cookies

If you want to know for sure that the cookie send from the client is not modified, you can encrypt the cookie.

Set the encrypted cookie:

Use the fourth parameter to Boolean true to set an encrypted cookie

Cookie :: add('foo', 'bar', 60, true);
Read the encrypted cookie:
echo Cookie :: get('foo'); //Output "bar"

Note: For this to work you need to set a salt in the app.php.

app.php:
//Salt
Application :: add('salt', 'this-should-be-a-unique-value'); //Edit the value to a unique value for your application