note 54266 added to function.setcookie

From: Date: Wed, 29 Jun 2005 04:32:05 +0000
Subject: note 54266 added to function.setcookie
Groups: php.notes 
Request: Send a blank email to php-notes+get-91108@lists.php.net to get a copy of this message
This is a simple problem but I saw it come up in a few forums so I might as well post it. When setting a cookie you will need to refresh the page before the browser actually reads the cookie. Meaning if you were setting a log-in cookie through a form, and the action of the form is the page itself (lets say you were on index php and, after the submit button is pressed and the script is executed, index.php loads again), you would need to reload the page if you wanted to display the cookie for example. An easy fix for this is to add a header("Location:index.php"); function after the setcookie() function. The browser will read the cookie the first time it reloads after the form button is pressed. My log in script looks like this. <?php include("connect.php"); $match= "SELECT id FROM members WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."';"; $qry = mysql_query($match); $num_rows = mysql_num_rows($qry); //*******create login or logout if("LogIn" == $Loggin){ if ($num_rows > 0) { setcookie("loggedin", "TRUE", 0); setcookie("talentrewards_username", "$username") ; //********refresh automatically when cookie is set. header("Location:index.php"); }else{ echo ("Sorry, there is no username $username with the specified password.<br><br>"); } } if("LogOut" == $Loggin){ setcookie("loggedin", "FALSE"); //********refresh automatically when cookie is set. header("Location:index.php"); } ?> ---- Manual Page -- http://www.php.net/manual/en/function.setcookie.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+54266 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54266&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54266&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54266&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54266&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54266&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54266&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+54266&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#91108) next »