Re: setting a cookie from a form value

From: Date: Thu, 13 Aug 2020 07:07:04 +0000
Subject: Re: setting a cookie from a form value
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-327279@lists.php.net to get a copy of this message
> On Aug 12, 2020, at 10:21 PM, Ashley Sheridan <ash@ashleysheridan.co.uk> wrote: > > > > On August 10, 2020 9:58:04 PM UTC, Fernando Fiore <no5software@gmail.com> wrote: >> <?php >> // this fails twice before working >> // first with undefined index 'txt' on line 5 >> // then with undefined index 'val' on line 10 then it works >> $name = $_POST['txt']; >> setcookie("val",$name,time() + 24 * 60 * 60); >> >> if(isset($_COOKIE) && !empty($_COOKIE)) >> { >> $var = $_COOKIE['val']; >> print('cookie = '. $var . '</br>'); >> } >> else >> echo ' cookie not set </br>'; >> >> >> >> ?> >> <form action="cookie2.php" name="myform" method="post"> >> <input type="text" name="txt" id="txt" >> value="abcdef" /> >> <input type="submit" formmethod="post" /> >> </form> > > It will, you're trying to access variables before they're set. You can use isset() to > check those. > > On that topic, you're using isset on $_COOKIE, but that global array will always be there > (unless you're using PHP CLI), so the check is redundant. > Thanks, > Ash It would be better to do: if( isset($_COOKIE['val']) ) { print $_COOKIE['val']; } Because $_COOKIE['val'] is what you are setting to begin with. JK

« previous php.general (#327279) next »