What does “the value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received” mean?

末鹿安然 提交于 2019-12-02 12:08:45

Http cookies are headers that are transferred between the client (the browser), and the webserver.

When you use setcookie, what you are doing is instructing the PHP interpreter to inject a header in its response with this format:

Set-Cookie:name=value

That cookie will be stored by the browser, and returned by it in future requests (to the same host) in the Cookies request header like this:

Cookie:name=value;cookie2=value;cookie3=value

Normally, when transferring this you should urlencode any special characters. Let's say that I wan to specify a cookie named "operator" with a value of ">", then I should emit this header:

Set-Cookie:operator=%3E

When it says that the value is automatically urlencoded, is saying that you don't have to worry about that. You can simply do:

setcookie('operator', ">");

And PHP will handle the urlencoding directly, producing the correct header.

On the server side, you'll receive cookies in the $_COOKIES superglobal, and in the same way that happens with $_GET and $_POST, values will be automatically urldecoded for you. So if the client returns the previously set cookie %3E, you'll see: > in your code.

If you use your browser inspector, you can see the relevant headers on any request-response. E.g.:

request (returning cookie)

response (setting cookie)

setrawcookie, does the same, but you have to urlencode on your own. From the docs:

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.

More likely than not, you won't have any reason to ever use setrawcookie directly.

From where the cookie is being sent to whom and at where the cookie is being received from whom?

Initially the cookie will be sent from the server to the browser. In every subsequent request, the browser will send it back to the server.

What actually does happen by means of "Value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received"?

There are limits on what characters can appear in a cookie. URL encoding converts those characters to a different representation to make them valid.

You don't need to do that yourself because the PHP setcookie method will do it for you, and the $_COOKIE variable will contain the decoded versions by the time your code interacts with it.

What role does setrawcookie() play? I mean what it actually does?

It lets you set a cookie without that encoding (so you have to encode it manually). You should probably never need to use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!