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 Mikey - 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 ross - November 1, 2016
Hi Zicky
I have a solution for you to try. It involves restructuring your code a bit:
// get current ticket id from cookie
$currentTicketID = @$_COOKIE['ticket_id'];
// if there is no cookie already set
// create new cookie
if (!$currentTicketID) {
$digits = mt_rand();
//echo $digits; //prints random numbers
$number_of_days = 30 ;
$date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
setcookie( 'ticket_id', $digits, $date_of_expiry );
}
Give that a shot and let me know how you make out.
Thanks.
Cheers,
Ross Fairbairn - Consulting
consulting@interactivetools.com
Hire me! Save time by getting our experts to help with your project.
Template changes, advanced features, full integration, whatever you
need. Whether you need one hour or fifty, get it done fast with
Priority Consulting: http://www.interactivetools.com/consulting/