denis
denis

Reputation: 23

Error when checking if a cookie is set

I am using this in my controller to check if a cookie was already set. If not, I set it.

function x(){
    if(!isset($_COOKIE['sg'])){
        $this->load->model('generate_model');
        $val=$this->generate_model->random();
        setcookie('sg',$val, time()+3600*24*30*12*3,"/", "" );
    }
    $this->load->model('model');
    $data['cod']=$cod;
    $this->model->select($cod);
    $this->load->view('templates/header');
    redirect('Home','refresh');
}

If the cookie was not set, I get two errors:

A PHP Error was encountered

Severity: Notice

Message: Undefined index: sg

Filename: models/select_gift_model.php

Line Number: 12

A Database Error Occurred

Error Number: 1048

Column 'uid' cannot be null

INSERT INTO id ( uid, cod) VALUES ( NULL, '35A5V0Mogc')

Filename: C:\wamp\www\ci\system\database\DB_driver.php

Line Number: 330

The cookie is set, and if I press back and call again, the function works normally.

How can I check if a cookie is set and make the function work properly?

Upvotes: 1

Views: 82

Answers (1)

MKroeders
MKroeders

Reputation: 7742

In the docs of php:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

Source: http://php.net/manual/en/function.setcookie.php

THe best way to make it also in the current connection available is to do the folling:

setcookie('sg',$val, time()+3600*24*30*12*3,"/", "" );
$_COOKIE = $val;

Upvotes: 1

Related Questions