Jump to content

cookie coding


westman

Recommended Posts

Hi all,
I am coding cookies for the first time and here is what I have.

setcookie("username", $old_cookie, "1", "/", "", "", TRUE);
setcookie("username", $new_cookie, strtotime( '+30 days' ), "/", "", "", TRUE);


Is this the right way of resetting the value of one cookie?

ps. I did read a lot on http://php.net/manual/en/function.setcookie.php but it is not clear.

Link to comment
Share on other sites

To delete a cookie, set its expiry date to a past date. If you set the same cookie twice the first one will be ignored. You're not actually deleting the cookie, you're giving it a different value.

Link to comment
Share on other sites

I see,
so to give my cookie an updated value will this code work?

setcookie("username", $old_cookie, strtotime( '-30 days' ), "/", "", "", TRUE);
setcookie("username", $new_cookie, strtotime( '+30 days' ), "/", "", "", TRUE);

 

Link to comment
Share on other sites

On loading of the page the first time NOTHING if the cookie does not already exist, but the cookie will be set by the second line. The second time the page is loaded because the cookie now exists, the first line will cause it to be deleted, then the second line will set it again and the circle will start over delete, set on page load, delete, set on page load and so on...

Quote

What happens to the cookie when it hits 30 days old from my script?   

It will be deleted.

NOTE: With your current code, it won't expire i.e be deleted, as the expiry date increases by 30+ days from current date everytime time it is loaded.

Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

Error update.
Using this code...

$new_cookie = "123456789abcdefg";
setcookie("username", $new_cookie, strtotime( '+30 days' ), "/", "", "", TRUE);
echo $_COOKIE["username"];
echo "<br />";
print_r($_COOKIE);


the output is still an error.
 

Capture.PNG

Link to comment
Share on other sites

You can only retrieve set cookie data on the second request for example reloading of same page again, or goes to another page and retrieves it then.

http://php.net/manual/en/function.setcookie.php

Quote

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 expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

 

Edited by dsonesuk
Link to comment
Share on other sites

You cannot read a cookie during the same request when you set it, it was not sent by the browser.  Cookies are sent in the HTTP headers.  So when you set a cookie, you are telling the browser to save it and send it back on the next request.  The new cookie is not part of the current request, because when the browser sent the headers it did not have the cookie yet, the cookie was only set by the response headers from the server.

Link to comment
Share on other sites

It seems the error relates to sessions not cookies, and since it says line 94, In my mind its not related to the cookie code you have supplied.

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<?php
$new_cookie = "123456789abcdefg";
setcookie("username", $new_cookie, strtotime('+30 days'), "/", "", "", TRUE);
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />
        <title>Document Title</title>
        <script type="text/javascript">

        </script>
        <style type="text/css">

        </style>
    </head>
    <body>

        <?php
        echo $_COOKIE["username"];
        echo "<br />";
        print_r($_COOKIE);
        ?>
    </body>
</html>

This is what we are discussing.

  • Like 1
Link to comment
Share on other sites

I am trying so hard to understand, I am.
If someone could provide code of a working example that would be grate to understand from there.

I now have this code on one page of my site...
setcookie("username", $new_cookie, strtotime( '+30 days' ), "/", "", "", TRUE);

and this code on a different page...
if(isset($_COOKIE['username'])){
echo "1";
}else{
echo "0";
}

my output is 0 every time.
I am not successful at setting my first cookie

 

Link to comment
Share on other sites

The setcookie() call has to be done before any HTML is printed, even before the <!DOCTYPE> declaration, because cookies are sent with the headers which have to go before the content.

  • Like 1
Link to comment
Share on other sites

Indeed, kind of embarrassing to post an example where you send output before trying to set a cookie with a header.

The error message with the header tells you where output was sent (in the case of the error message above, line 2), and where you tried to send a header by calling the header or setcookie functions (line 94 in that error message).  You need to move anything that sends a header before any output.  So, in the case of that error message, you need to set the cookie before line 2 (or just don't send any output at all until PHP is finished processing the request).

  • Like 1
Link to comment
Share on other sites

I am using...
echo "<script>setTimeout(\"location.replace('http://mysite.com?p=dashboard')\",1000)</script>";
at the bottom of my login script.
What code can I use where a cookie will be set and I can move my user to a different page? 

 

Just testing this code and its not the issue.

Edited by westman
Link to comment
Share on other sites

Okay I got the biggest puzzle since early man.

here is my code..

if (isset($_GET['active'])) {
$active = $_GET['active'];
if ($active == "logout"){

if(isset($_COOKIE["username"])){
setcookie("username", '', strtotime( '-5 days' ), '/');
}
session_destroy();
// This code removes the cookie no problem. However it shows the header error
echo "<script>setTimeout(\"location.replace('http://mysite.com')\",1000)</script>";
// this code does not show the header error but need to run the url (mysite/?active=logout) twice to kill the cookie (session destroy works just fine)
header("location: http://www.mysite.com");
}
}

What do I do here?
 




 

Link to comment
Share on other sites

1 hour ago, dsonesuk said:

HMMM, strange that, It states here

https://www.w3schools.com/php/func_http_setcookie.asp

and here

http://php.net/manual/en/function.setcookie.php

It needs to be before <html>

The PHP manual says prior to any output. The reason being that it has to be in the HTTP headers section. If you have studied the HTTP protocol it should be clear.

An HTTP response consists of two sections: The headers and the body. The headers provide information about the data being sent, such as the amount of bytes, the file type and also cookies. After the headers goes two line breaks and then the body. The body is the actual file contents. In order to be efficient, PHP goes sending data back to the client while it is still processing, which means that as soon as any content is printed, whether it be HTML or anything else, it immediately sends the two line breaks and enters the body section of the HTTP response. Once those two line breaks have been sent it is impossible to go back an send any more headers to the client because whatever you send is going to be considered part of the body.

While PHP is usually used to send HTML, it can also send any other kind of content, like image data, a video or an excel file. PHP can output content of any kind, so saying that headers have to be sent before the <html> tag just covers the specific case that the first part of your output is the string "<html>".  The general case is that the headers have to be sent prior to any output.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...