What are cookies ? How to create cookies in PHP ?

  • In PHP cookie is a small file with a maximum size of 4KB that the web server stores on the client computer.
  • Cookies are typically used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time.
  • They can only be read from the domain that it has been issued from.
  • In browser cookies are usually set in an HTTP header but JavaScript can also set a cookie directly.
  • In PHP setcookie () function is used to set a cookie.
  • This function needs to be called prior to any output generated by the script otherwise the cookie will not be set.
  • In setcookie () function name parameter is used to set the name of the cookie and value parameter is used to set the value of the cookie.
  • In setcookie () function expire parameter is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
  • In setcookie () function path parameter is used to specify the path on the server for which the cookie will be available.
  • In setcookie () function domain parameter is used to specify the domain for which the cookie is available.
  • In setcookie () function security parameter is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.

Syntax

[pastacode lang=”php” manual=”setcookie%20(name%2C%20value%2C%20expire%2C%20path%2C%20domain%2C%20security)%3B” message=”” highlight=”” provider=”manual”/]

Sample Code

[pastacode lang=”php” manual=”%3C!DOCTYPE%20html%3E%0A%3C%3Fphp%0Asetcookie(%22test_cookie%22%2C%20%22test%22%2C%20time()%20%2B%203600%2C%20’%2F’)%3B%0A%3F%3E%0A%3Chtml%3E%0A%3Cbody%3E%0A%0A%3C%3Fphp%0Aif(count(%24_COOKIE)%20%3E%200)%20%7B%0A%20%20%20%20echo%20%22Cookies%20are%20enabled.%22%3B%0A%7D%20else%20%7B%0A%20%20%20%20echo%20%22Cookies%20are%20disabled.%22%3B%0A%7D%0A%3F%3E%0A%0A%3C%2Fbody%3E%0A%3C%2Fhtml%3E%0A” message=”” highlight=”” provider=”manual”/]

Output

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like