Cara menggunakan php cookies not working

Cookie: A Cookie is a small file sent by the server to preserve stateful information for a user. It is stored on the client’s computer and sent to the server every time the user makes a request for the same page.

To create cookies you can set the cookie by using the setcookie[] function of the PHP.

Syntax: 

setcookie[name, value, expire, path, domain, secure, httponly]

Parameters: This function accepts seven parameters as mentioned above and described below:  

  • name: The name of the cookie.
  • value: The value you want to store in the cookie.
  • expire-time: It is the number of seconds until the cookie will be kept on the user’s machine by the browser. After that, it will automatically be deleted. If not set then the cookie will be preserved by browser until it is open.
  • path: It determines for which directories cookie will valid. If you want to access it in all directories then put it on “/”, i.e. the cookie is accessible in the entire domain. Otherwise, the cookie will be limited to the subdirectory.
  • domain: It is used to define the access hierarchy for the cookie. For example, if you set this to “yourdomain.com”, it will be accessible via all the subdomains also. but if it set to “sub.yourdomain.com”, it will be accessible by “sub.yourdomain.com” and its subdomains.
  • secure: It determines how the cookie will be sent, via HTTP or HTTPS. If set to true then the cookie will be sent via HTTPS only, otherwise, it will be sent via HTTP. Its default value is false.
  • httponly: If it set to true, the cookie is accessible only either via HTTP or HTTPS. That means the client code [like Javascript] can not access the cookie.

Out of the above parameters, only the first two parameters are mandatory. Others are optional parameters. If you want to preserve the cookie, then provide the expire-time parameter.

Note: It is stored in the global array named $_COOKIE.

Creating a Cookie: As mentioned earlier, we can set cookies by using the function setcookie[].  

  • Example: 

PHP

    

    

Bài mới nhất

Chủ Đề