Php session cookie browser close

how to delete all cookies of my website in php

I’m wondering if I can delete all my website’s cookies when a user click on logout, because I used this as function to delete cookies but it isn’t work properly:

In most cases, the better idea will be to use cookies more wisely selectively. If you use sessions, one cookie will be sufficient. Anyway, track which cookies you set, then you won’t need some dynamic way of iterating over them and deleting them.

12 Answers 12

Taken from that page, this will unset all of the cookies for your domain:

// unset cookies if (isset($_SERVER['HTTP_COOKIE'])) < $cookies = explode(';', $_SERVER['HTTP_COOKIE']); foreach($cookies as $cookie) < $parts = explode('=', $cookie); $name = trim($parts[0]); setcookie($name, '', time()-1000); setcookie($name, '', time()-1000, '/'); >> 

I read that comment, but I really don’t get why using the HTTP_COOKIE value would be any better than looping through the $_COOKIE array. Do you have any reason for that? To me it only looks like more (double) work for the parser.

@poke: If cookie names are in Array notation, eg: user[username] Then PHP will automatically create a corresponding array in $_COOKIE. Instead use $_SERVER[‘HTTP_COOKIE’] as it mirrors the actual HTTP Request headers.

I’ve seen situations where there are 2 cookies with the same name, but with different domain settings. One of them will make it into the $_COOKIE array, and the other won’t. But they will both be visible in HTTP_COOKIE. If you want to clean this situation up, this is the way to do it.

$past = time() - 3600; foreach ( $_COOKIE as $key => $value ) < setcookie( $key, $value, $past, '/' ); >

Even better is however to remember (or store it somewhere) which cookies are set with your application on a domain and delete all those directly.
That way you can be sure to delete all values correctly.

great code, but isn’t enought to use setcookie( $key, FALSE ); ?! (see Notes scetion at php.net/manual/en/function.setcookie.php)

@Marco Demaio: It should be, but I have seen that fail in the past on some servers. But of course, if it works for you, just do it like that 🙂

it shouldn’t be a matter of server, it’s the PHP that does it internally. And what’s the need of the final / you placed in setcookie ?

@Marco Demaio: Yeah, with server I meant the php server. The / is the cookie path. You need to set it so that you can remove the cookies from the domain, otherwise it is set to the current path, and only affects those that are set for the current path.

I agree with some of the above answers. I would just recommend replacing «time()-1000» with «1». A value of «1» means January 1st, 1970, which ensures expiration 100%. Therefore:

setcookie($name, '', 1); setcookie($name, '', 1, '/'); 

I’ve always wondered why no one says to just do this, and is kind of the answer I’ve been looking for.

Possibly not an issue currently, but at one point some browsers ignored a date that old all together, and the values wouldn’t be discarded as they should. I believe IE 7 is one example that did this.

Читайте также:  Bool var in python

The provided Answers did not solve my problem,

  1. Remove parent domain cookies (from a.b.c; remove b.c; cookies),
  2. Remove cookies from a higher path other then root.
 $parts = explode('/', $uri); $cookiePath = ''; foreach ($parts as $part) < $cookiePath = '/'.ltrim($cookiePath.'/'.$part, '//'); setcookie($name, '', 1, $cookiePath); $_domain = $domain; do < setcookie($name, '', 1, $cookiePath, $_domain); >while (strpos($_domain, '.') !== false && $_domain = substr($_domain, 1 + strpos($_domain, '.'))); > > 

It is not the most pretty/safe/optimal solution, so use this only if you do not known the cookie-path and/or cookie-domain’s. Or use the idea in order to create your version.

make sure you call your setcookie function before any output happens on your site.

also, if your users are logging out, you should also delete/invalidate their session variables.

When you change the name of your Cookies, you may also want to delete all Cookies but preserve one:

You should be aware of various tracking tools like Google Analytics also use cookies on your domain and you don’t want to delete them, if you want to have correct data in GA.

The only solution I could get working was to set the existing cookies to null. I couldn’t delete the cookies from the client.

So for logging a user out I use the following:

setcookie("username", null, time()+$this->seconds, "/", $this->domain, 0); setcookie("password", null, time()+$this->seconds, "/", $this->domain, 0); 

Of course this doesn’t delete ALL cookies.

Источник

setcookie

Alternative signature available as of PHP 7.3.0 (not supported with named parameters):

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST .

Parameters

» RFC 6265 provides the normative reference on how each setcookie() parameter is interpreted. name

The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is ‘cookiename’ , this value is retrieved through $_COOKIE[‘cookiename’]

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. One way to set this is by adding the number of seconds before the cookie should expire to the result of calling time() . For instance, time()+60*60*24*30 will set the cookie to expire in 30 days. Another option is to use the mktime() function. If set to 0 , or omitted, the cookie will expire at the end of the session (when the browser closes).

Note:

You may notice the expires_or_options parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT , this is because PHP does this conversion internally.

The path on the server in which the cookie will be available on. If set to ‘/’ , the cookie will be available within the entire domain . If set to ‘/foo/’ , the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

Читайте также:  Html css javascript classes

The (sub)domain that the cookie is available to. Setting this to a subdomain (such as ‘www.example.com’ ) will make the cookie available to that subdomain and all other sub-domains of it (i.e. w2.www.example.com). To make the cookie available to the whole domain (including all subdomains of it), simply set the value to the domain name ( ‘example.com’ , in this case).

Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to true , the cookie will only be set if a secure connection exists. On the server-side, it’s on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER[«HTTPS»] ).

When true the cookie will be made accessible only through the HTTP protocol. This means that the cookie won’t be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. true or false

An associative array which may have any of the keys expires , path , domain , secure , httponly and samesite . If any other key is present an error of level E_WARNING is generated. The values have the same meaning as described for the parameters with the same name. The value of the samesite element should be either None , Lax or Strict . If any of the allowed options are not given, their default values are the same as the default values of the explicit parameters. If the samesite element is omitted, no SameSite cookie attribute is set.

Return Values

If output exists prior to calling this function, setcookie() will fail and return false . If setcookie() successfully runs, it will return true . This does not indicate whether the user accepted the cookie.

Changelog

Version Description
8.2.0 The date format of the cookie is now ‘D, d M Y H:i:s \G\M\T’ ; previously it was ‘D, d-M-Y H:i:s T’ .
7.3.0 An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.

Examples

Some examples follow how to send cookies:

Example #1 setcookie() send example

$value = ‘something from somewhere’ ;

setcookie ( «TestCookie» , $value );
setcookie ( «TestCookie» , $value , time ()+ 3600 ); /* expire in 1 hour */
setcookie ( «TestCookie» , $value , time ()+ 3600 , «/~rasmus/» , «example.com» , 1 );
?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don’t want this, you can use setrawcookie() instead. To see the contents of our test cookie in a script, simply use one of the following examples:

// Print an individual cookie
echo $_COOKIE [ «TestCookie» ];

// Another way to debug/test is to view all cookies
print_r ( $_COOKIE );
?>

Читайте также:  Style MySQL table with CSS

Example #2 setcookie() delete example

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

// set the expiration date to one hour ago
setcookie ( «TestCookie» , «» , time () — 3600 );
setcookie ( «TestCookie» , «» , time () — 3600 , «/~rasmus/» , «example.com» , 1 );
?>

Example #3 setcookie() and arrays

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie’s name:

// set the cookies
setcookie ( «cookie[three]» , «cookiethree» );
setcookie ( «cookie[two]» , «cookietwo» );
setcookie ( «cookie[one]» , «cookieone» );

// after the page reloads, print them out
if (isset( $_COOKIE [ ‘cookie’ ])) foreach ( $_COOKIE [ ‘cookie’ ] as $name => $value ) $name = htmlspecialchars ( $name );
$value = htmlspecialchars ( $value );
echo » $name : $value
\n» ;
>
>
?>

The above example will output:

three : cookiethree two : cookietwo one : cookieone

Note: Using separator characters such as [ and ] as part of the cookie name is not compliant to RFC 6265, section 4, but supposed to be supported by user agents according to RFC 6265, section 5.

Notes

Note:

You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expires_or_options parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE); .
  • Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to ‘deleted’ and expiration time in the past.
  • Because setting a cookie with a value of false will try to delete the cookie, you should not use boolean values. Instead, use 0 for false and 1 for true .
  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user’s system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.

Multiple calls to setcookie() are performed in the order called.

See Also

  • header() — Send a raw HTTP header
  • setrawcookie() — Send a cookie without urlencoding the cookie value
  • cookies section
  • » RFC 6265
  • » RFC 2109

Источник

Оцените статью