setcookie in PHP

setcookie in PHP

The setcookie() function in PHP is used to set a cookie in the user’s browser. A cookie is a small piece of data that is stored on the user’s computer and can be accessed by the server on subsequent requests. Cookies are commonly used to store user preferences, login information, and other data that needs to persist between requests.

The setcookie() function accepts up to seven parameters:

  • name: the name of the cookie.
  • value: the value of the cookie.
  • expires: the expiration time of the cookie in Unix timestamp format. If not set, the cookie will expire when the browser is closed.
  • path: the path on the server where the cookie will be available.
  • domain: the domain where the cookie will be available.
  • secure: indicates whether the cookie should only be transmitted over a secure HTTPS connection.
  • httponly: indicates whether the cookie should only be accessible through HTTP requests, and not through client-side scripting languages like JavaScript.

Here’s an example of setting a cookie in PHP:

// Set a cookie with the name "username" and value "john"
setcookie("username", "john", time() + 3600, "/");

In this example, the setcookie() function sets a cookie with the name "username", value "john", and an expiration time of one hour (time() + 3600). The cookie is available on the root path of the website ("/").

You can also retrieve the value of a cookie using the $_COOKIE superglobal array. For example:

// Retrieve the value of the "username" cookie
echo $_COOKIE["username"];

In this example, the $_COOKIE superglobal array is used to retrieve the value of the "username" cookie. Note that cookies can only be accessed on subsequent requests, so the value of the cookie may not be available immediately after setting it with setcookie().

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Primary Market
setrawcookie in PHP

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?