PHP (setcookie) vs header (header )

Asked

Viewed 888 times

5

I see some frameworks, CMS and the like, writing cookies directly in PHP with setcookie and others stock to send us headers at the end of the run. I wanted to know how to create a pattern for the creation of cookies.

PHP

The setcookie() function sets a cookie to be sent along with the rest of the HTTP headers


We should create by sending by header?

header( "Set-Cookie: {$name}={$value};" )

Or leave it to PHP?

setcookie( $name , $value )

  • I recommend using setcookie() as it is an appropriate function to do this type of action. Header() is also good, but we recommend using setcookie()

  • 1

    Another thing (that by now you should know) is that with header would have to use urlencode or rawurlencode. The following code is available on Github: https://github.com/php/php-src/blob/71c19800258ee3a9548af9a5e64ab0a62d1b1d8e/ext/standard/head.c#L80

  • @Guilhermenascimento, I didn’t know that. He would have to use domain?

  • 1

    @Papacharlie then by what I analyzed from php source code it is necessary only name and value to be encoded, others not.

1 answer

5


Both functions come to the same result.

But what differentiates the setcookie() is its ease for creating more complex cookies, with expiration date, domain of the application that the cookie will be used (www.algumacoisa.com.br), among others.

See all parameters the function accepts:

setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

More information on php documentation.

  • 2

    I have no doubt how to create them, it was just a matter of choosing the method(A or B). I have my class Cookie with all attributes for cookies and is currently with setcookie, I will keep as standard. Thank you

  • 2

    Just one addition: the setrawcookie has the same facilitator that gmsantos said, but he does not use urlencode value. Therefore, I see no need to use header in the case of PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.