Prevent error message, Check if $_COOKIE exist, if not create cookie

3 posts by 2 authors in: Forums > CMS Builder
Last Post: November 1, 2016   (RSS)

By Zicky - October 27, 2016

I need to check and see if a cookie exist for 'ticket_id', and if it does not, then set a cookie for 'ticket_id'.  The 'ticket_id' are numbers generated by $digits, which are then stored in the cookie.

The code below throws the following error on the initial loading of the site page, because no cookie exist as of the first site visit. 

Notice: Undefined index: ticket_id in /home/abcd/public_html/ticket.php on line 35

Once the site page is reloaded the error goes away, because a cookie for 'ticket_id' has been created and populated with numbers generated by $digits and the cookie (on page reload) now exist for the visitor.

Anyone have any suggestions on how to prevent the "Notice" error message on the initial site visit - where a site visitor does not have a cookie assigned to them as of yet? Or have a better suggestion on creating the cookie?

$digits = mt_rand();
//echo $digits; //prints random numbers
$number_of_days = 30 ;
$date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
if(!isset($_COOKIE['ticket_id'])) {
setcookie( 'ticket_id', $digits, $date_of_expiry );
}
$getcookie = $_COOKIE['ticket_id'];

// Throws error seen below on the first load of the site page, because no cookie exist yet: 
// Notice: Undefined index: ticket_id in /home/abcd/public_html/ticket.php on line 35

I tried the code below with ($_COOKIE['ticket_id'] = '0' ;), but it throws off my 'ticket_id' numbers generated by $digits - which should remain the same number once the cookie is set.

$digits = mt_rand();
//echo $digits; //prints random numbers
$_COOKIE['ticket_id'] = '0' ;
$number_of_days = 30 ;
$date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
if(!isset($_COOKIE['ticket_id'])) {
setcookie( 'ticket_id', $digits, $date_of_expiry );
}
$getcookie = $_COOKIE['ticket_id'];

Thanks, Zicky

By Zicky - November 1, 2016

Thanks for the help Ross!!!

Works like a charm.

Zicky