zlatangu Posted March 5, 2015 Share Posted March 5, 2015 I have a problem, each time that i reload the page i get a different $num variable why is that happening? Can somebody help me, i'm beginner in php. <?php if(isset($_COOKIE["nums"])){ $num = $_COOKIE['nums']; }else{ $num = rand(1,9).date('Y').date('m').date('d').date('h').date('i').date('s'); setcookie("nums",$num, 9999999999); } echo "You have " .$num. " ...."; ?> Link to comment https://forums.phpfreaks.com/topic/295133-help-with-setcookie-function/ Share on other sites More sharing options...
cyberRobot Posted March 5, 2015 Share Posted March 5, 2015 The code seems to work for me. Do you have cookies disabled? Note that the code could be simplified a bit by calling date() once. $num = rand(1,9).date('Ymdhis'); Link to comment https://forums.phpfreaks.com/topic/295133-help-with-setcookie-function/#findComment-1507684 Share on other sites More sharing options...
CroNiX Posted March 6, 2015 Share Posted March 6, 2015 The thing I noticed is your expiration time. It's a unix timestamp. If I enter echo date('Y-m-d H:i:s', 9999999999); I get 2014-09-06 21:50:07 So it means the cookie is already expired. Link to comment https://forums.phpfreaks.com/topic/295133-help-with-setcookie-function/#findComment-1507721 Share on other sites More sharing options...
mac_gyver Posted March 6, 2015 Share Posted March 6, 2015 are you getting a header error due to outputting something (or even your file having been saved with a byte order mark character) before the setcookie() statement? having php's error_reporting/display_errors set to report and display all php errors, when debugging code problems, will help. Link to comment https://forums.phpfreaks.com/topic/295133-help-with-setcookie-function/#findComment-1507774 Share on other sites More sharing options...
cyberRobot Posted March 6, 2015 Share Posted March 6, 2015 The thing I noticed is your expiration time. It's a unix timestamp. If I enter echo date('Y-m-d H:i:s', 9999999999); I get 2014-09-06 21:50:07 Hmm...for some reason, I get "2286-11-20 09:46:39". @zlatangu - The documentation for setcookie() recommends that you use the time() function when setting the expiration date. Here is an example provided in the manual: <?php $value = 'something from somewhere'; setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */ ?> Link to comment https://forums.phpfreaks.com/topic/295133-help-with-setcookie-function/#findComment-1507779 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.