Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cookie not setting 1

Status
Not open for further replies.

LWolf

Programmer
Feb 3, 2008
77
US
I have done the research on setting a cookie and I cannot get it to set...

First I tried the data I needed...
Code:
if (isset($_POST['slocation'])!=""){
    	setcookie("slocation", $_POST['slocation'], time()+60*60*24*365*10;);
        echo "SLOCATION=" . $_POST['slocation'] . "<br>"; //used to see if getting into the if statement...it gets here//
    }

After the above code doesn't work I tried a basic one...
Code:
setcookie("user", "keith");

And that is not working. My browser is set to accept cookies. What am I doing wrong?!

Thanks,
K
 
try this please.
Code:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
if(isset($_COOKIE) && isset($_COOKIE('mytestcookie')):
  print_r($_COOKIE['mytestcookie']);
endif;
setcookie('mytestcookie', 'mytestcookievalue', time() + 2592000);
?>
<script type="text/javascript">
 setTimeout(function(){
   location.reload(true);
 }, 5000);
</script>
 
I copied and pasted. Here is the result...

Fatal error: Can't use function return value in write context in ///index.php on line 132
 
well. that's most confusing as the code i posted only had ten lines or so; so quite how there can be an error on line 132 is beyond me.

perhaps you have mixed it with another script?

the first stage of course is to ensure that the setcookie function is working.

then we can go on to check what is happening in your production script - although that error should give you enough to go on. if not post all the code around line 132.
 
This is the line that is throwing the error...

Code:
if(isset($_COOKIE) && isset($_COOKIE('mytestcookie')):
 
really?
that wasn't on line 132 of the code I posted. it was on line 7.
do bear in mind that this code should be run in a script on its own to test your cookie issue.

on that line hopefully you have spotted that the array key was in round brackets rather than square brackets

Code:
if(isset($_COOKIE) && isset($_COOKIE['mytestcookie']):

 
Parse error: syntax error, unexpected ':' in ///test.php on line 7
 
I bet you can't guess what that error is caused by?

..


Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
;-)

Put a close round bracket before the colon.
 
OK, it is printing the 'mytestcookievalue' and reloading.
 
then cookies work fine. you're all set.

i wonder how you are assessing that cookies 'do not work' as per your first post? different browsers commit the cookies to storage at different times. the reliable way to test is either to examine the headers that are being transmitted with the page request or to validate the cookies superglobal on page load.

 
I display the POST data to the screen and it is there.
I then set the cookie and echo the POST again to the screen with this code...
Code:
setcookie("user", "keith");
    if (isset($_POST['slocation'])!=""){
    	    $expire=time()+60*60*24*365*10;
        setcookie("slocation", $_POST['slocation'], $expire);
        echo "SLOCATION=" . $_POST['slocation'] . "<br>";
    }

I then echo to see the value of the cookie...
Code:
echo "COOKIE=" . $_COOKIE['slocation'] . "<br>";

The problem is that the result is "COOKIE=", the cookie is not set.
 
but the cookie won't appear until the page refresh, because it has not been send by the browser to the server.

setcookie() sends a header to the browser. the browser creates the cookie.
 
Even after refreshing multiple times there is no cookie.
 
when you used the code I provided you clearly had cookies. so you need to go back to square one with your code and work out where and why it is different.

if you care to provide your complete code we may be able to help you further.
 
No matter how I reload the page or set the cookie it does not work. I have tried to directly set the cookie with no other scripting to no avail, along with any variation of the code you provided intergected into my page. I'm at a total loss. This is all the code that pertains to any cookie outside setting the global session...

Code:
<Script language='javascript'>
//Determine if there is a store location cookie
function s_chk(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return true;        
    }
    if (document.productselection.slocation.value!="") {return true;}
    alert("You must select a store");
    return false;
}
</Script>


<?php     
    include 'db_connect.php';
    setcookie("user", "keith");
    if (isset($_POST['slocation'])!=""){
    	    $expire=time()+60*60*24*365*10;
        setcookie("slocation", $_POST['slocation'], $expire);
        echo "SLOCATION=" . $_POST['slocation'] . "<br>";
        echo "COOKIE=" . $_COOKIE['slocation'] . "<br>";
    }
    setcookie("slocation", "KeithsTest");
    ?>

The code is exactly like the page, nothing omitted or added. The top script checks if the cookie is set during "onsubmit" and if not forces the user to select a location in the form. The page loads itself with all the POST data. That is when the 2nd script determines if there was a location selection and should set the cookie. There is a variable that is set to the cookie if it exists or the variable if it does not exist. The problem is I do not want a user to select a location for every search. Do you need more code? The above code starts on line 96, everything above it is css. The page is only 415 lines, again the above code is the only place I am trying the cookie right until it sets.
 
I see.

From the manual

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 <html> and <head> tags as well as any whitespace.
 
That explains a lot. In ASP you can set most cookies anywhere at anytime. I got it working! Thank you
 
you can only do that in asp if the page content is set to buffer. usually that's undesirable for performance reasons.

you can do exactly the same in php of course. and in circumstances where you don't know whether or not the headers have been sent at any particular time, then it is sometimes useful. but nearly always better to refactor.
 
I know this is off topic...
I am working on the paging now and the FAQ here has been my beginning source code. In the buttons code it uses...
Code:
print '<a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page + 1) . '">next</a>';

In my testing I found that when using this the POST data is not send with it. Is there a way to send the data with the new page number?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top