I just started with OOP programming in PHP and I have made a cookie class.
With doing that i have got a few questions unanswered
-
is my class correct?
-
how do I use it properly in my page? ( lets think i want to see how many times the visitor visited my website before and output the result for the user )
I already tested it after loging in and using this code:
$cookie = new Cookie();
$cookie->store();
print_r($_COOKIE);
(I had a result thrown back but I don’t know if its the good result)
Bellow you can find my Cookie class.
<?php
class Cookie {
/* cookie $id */
private $id = false;
/* cookie life $time */
private $time = false;
/* cookie $domain */
private $domain = false;
/* cookie $path */
private $path = false;
/* cookie $secure (true is https only) */
private $secure = false;
public function __construct ($id, $time = 3600, $path = false, $domain = false, $secure = false) {
$this->id = $id;
$this->time = $time;
$this->path = $path;
$this->domain = $domain;
$this->secure = $secure;
}
public function store() {
foreach ($this->parameters as $parameter => $validator) {
setcookie($this->id . "[" . $parameter . "]", $validator->getValue(), time() + $this->time, $this->path, $this->domain, $this->secure, true);
}
}
public function restore() {
if (isset($_COOKIE[$this->id])) {
foreach ($_COOKIE[$this->id] as $parameter => $value) {
$this->{$parameter} = $value;
}
}
}
public function destroy() {
$this->time = -1;
}
}
?>
I hope someone can give me a good example! thanks for the help in advance!
This code should do the most frequent tasks you’ll need to manipulate cookies.
Don’t get confused by reading the getter and setter methods – they’re used to access the private variables defined in the class.
Have in mind this class is used per cookie and you need to have a new instance for every new cookie you’ll operate over.
Below the class I’ve added an example how to use the class.
P.S. I’ve commented the
$cookie->delete();on purpose so that you can see the content ofprint_r($cookie->get()).Edit:
Question: Where does the code go to see if the cookie is set?
Answer:
You should check what does $_COOKIE do in the php documentation.
Basically the server sends headers to the client’s browser which stores the cookies on the client’s computer. When the client initializes a connection to the server it passes the cookies with the request.
Question: Where goes the $cookie->delete();
Answer:
There isn’t a direct way to delete cookies. So in order to do that you need to create a cookie with the same name and expiration time which is in the past. When you do that the cookie is removed from the client’s browser.