user3217294
user3217294

Reputation: 3

How to create cookie

I have a problem regarding of creating cookies in PHP.

The scenario is this. I created a voting system in my site. And every user that will vote should be restricted up to 10 votes only. If the site detected that user it will automatically expired his/her cookies. And lastly after 3 months, all the user data (cookies) for that user will automatically destroyed.

How can I do that? Please help me I am in the middle of the project and I am a beginner in PHP. Thanks.

Controller

public function vote_photo() {  
  $vote = $this->contest_m->vote_photo($pid, fn_get_user('id'));
  $code = random_string('alnum', 42);

  if( ! empty($vote)){
    echo $vote['msg'];
    $cookie = array(
      'name'   => 'contest_cookies',
      'value'  => $code,
      'expire' => '7776000',
      'domain' => $this->input->server('HTTP_HOST'),
      'path'   => '/',
      'prefix' => 'sg_'
    );    
    $this->input->set_cookie($cookie);    
  }
  $data = array(
    'machine_id' => $_SERVER['REMOTE_ADDR'],
    'cookie' => $code ,
    'date' => '1',
    'photo_id' => '1',
    'contest_id' => '1'
  );
  $this->contest_m->save_cookie_count_ip($data);
  $this->input->set_cookie($cookie); 
}
}

Upvotes: 0

Views: 174

Answers (2)

Ashish Ratan
Ashish Ratan

Reputation: 2870

Syntax:

setcookie(name, value, expire, path, domain);

Example:

In the example below, we will create a cookie named "user" and assign the value "Ayushman-ashish" to it. We also specify that the cookie should expire after one hour:

<?php
setcookie("user", "Ayushman-ashish", time()+3600*24*30*3); // this is for 3 months
?>

Upvotes: 2

Owais
Owais

Reputation: 21

I am also a beginner but I found this helpful Set and send cookie examples..

<?php
$value = "Test Cookie value";

// send a simple cookie
setcookie("TestCookie",$value);
?>



<?php
$value = "Test Cookie value";

// send a cookie that expires in 24 hours
setcookie("TestCookie",$value, time()+3600*24);
?>

Upvotes: 0

Related Questions