PHP set cookie here in the Tutorial and more. An HTTP Cookie (Magic Cookie) is a small or short data packet that is exchanged between the website (domain) and the client (surfer). A cookie is sent from the server to the browser and placed at the client's computer. Or the cookie is generated directly with JavaScript and placed by the browser at the client. As long as the cookie is on the client's computer, it will send the data packet to the server with each new request of the website (domain). So this user can be identified and is no longer unknown to us, because we can create a profile the more often he visits the site.
Examples of data packets
The first question after you have probably figured out how cookies work, of course you want to know what to save now. So here are a few examples:
- Take a HTTP_USER_AGENT and get what we think is useful if the user agent exists.
- We could take the language with HTTP_ACCEPT_LANGUAGE
- We could encrypt the IP address and save it if it exists.
- We can collect everything for data, which pages visited, how long which page, length of stay ...
$_SERVER["HTTP_USER_AGENT"]
$_SERVER["HTTP_LANGUAGE"]
Here you will find even more server variables $_SERVER
You can use cookies for some, e.g. like a login system (this will also be set automatically at the session) or an online shop (for shopping cart).
PHP set cookie and fill and place packet
We build a function that simplifies and checks the creation of a cookie. In the first solution all variables are listed individually but it is enough if only the $ args variable is sent in.
In order to access the cookies later with JavaScript, we have to pay attention to three things. That's one that we put httponly on false and that we with json_encode as well as the name do not deal with any special characters.
Here is a function to place a cookie, this function can be anywhere in your script, however, calling this function must happen before something is output. So that means nothing else can be sent to the client (browser) before, neither with echo nor pure HTML.
0
/**
1
* PHP set cookie
2
* @param $agrs
3
*/
4
function setMyCookie( $agrs = ()) {
5
// Check if $args and header not sent
6
if ($agrs && !headers_sent($filename, $linenum)) {
7
/**
8
* Set cookie
9
* @see http://php.net/manual/de/function.setcookie.php
10
*/
11
setcookie(
12
$agrs[
13
$agrs['value'], // The value of the cookie, here you can use serialize
14
$agrs['expire'], // The time when the cookie becomes invalid
15
$agrs['path'], // The path on the server for which the cookie will be available
16
$agrs['domain'], // The domain to which the cookie is available
17
$agrs['secure'], // Specifies that the client's cookie should only be transferred over a secure HTTPS connection
18
$agrs['httponly'] // If set to TRUE, the cookie is only accessible via HTTP protocol
19
);
20
}
21
//.. is header sent or no args then do this
22
else {
23
// Check if header variables
24
if (isset($filename) && isset($linenum)) {
25
// trigger_error("Cookie" . $agrs['name'] . " could not be set on $filename line $linenum.", E_USER_ERROR);
26
}
27
return false;
28
}
29
}
So könnte dann Dein array aussehen was Du reinschicken wirst, siehe oben, dort haben wir alles beschriftet mit Kommentaren.
0
$agrs = (
1
"name" => 'Visitor',
2
"value" => json_encode(0, "sites" => ())), // Dynamische variablen, die bei jedem Aufruf oder in bestimmten Zeit abständen aktualisiert werden können
("totalvisits" => 3
"expire" => (time() + 2592000),
4
"path" => "/",
5
"domain" => "localhost",
6
"secure" => false,
7
"httponly" => false // Wenn nicht false dann können wir mit JavaScript nicht drauf zugreifen
8
);
9
10
// Aufruf unserer Funktion
11
setMyCookie($agrs);
We fill in everything we need and send it in to save this data which is in value. With expire we set the expiration time. At path we allow with the slash that this cookie on the whole web page access, however we could limit the access on certain sides. Domain is credible self-explanatory :) like this, secure is for HTTPS for secure connections and httponly for HTTP access only.
Reading the packet
Of course, we also want to read and evaluate our cookies. And there is also a PHP solution, you can address a cookie directly or all at once.
0
/**
1
* This function gets the cookie
2
* @param type $name
3
* @return type
4
*/
5
function getMyCookie($name = ") {
6
7
if (isset($_COOKIE[
8
return unserialize($_COOKIE[$name]);
9
}
10
}
0
/**
1
* This function gets the cookie
2
* @param type $args
3
* @return type
4
*/
5
function getMyCookie($args = ()) {
6
return (isset($args[]) : $_COOKIE);
7
}
8
9
// Alle Cookies
10
'<pre>';
11
var_dump(getMyCookie());
12
'</pre>';
13
14
// A specific cookie that we have set up with the name visitor
15
'<pre>';
16
var_dump(getMyCookie('Visitor')));
("name" => 17
'</pre>';
// A specific cookie that we have set up with the name visitor
object(stdClass)#1 (2) {
["totalvisits"] => int(0)
["sites"] => string(0)
}
// After calling again in combination with hasMyCookie () and update Cookie ()
object(stdClass)#1 (2) {
["totalvisits"] => int(2)
["sites"]=>
object(stdClass)#3 (2) {
["second"]=>
object(stdClass)#2 (2) {
["url"] => string(36) "Sites/NetBeans/PHP-Cookie/second.php"
["hits"] => int(1)
}
["index"]=>
object(stdClass)#4 (2) {
["url"] => string(35) "Sites/NetBeans/PHP-Cookie/index.php"
["hits"] => int(1)
}
}
}
// In JavaScript
{totalvisits: 2,
sites:
index: hits: 1 url: "Sites/NetBeans/PHP-Cookie/index.php"
second: hits: 1 url: "Sites/NetBeans/PHP-Cookie/second.php"
}
Updating the packet
We also want to keep the information in our cookie up to date and follow up profilers as well as possible in the same way as the user and record each of his steps.
0
/**
1
* This function update the cookie by name
2
* @param type $name
3
* @return type
4
*/
5
function updateMyCookie($name = '') {
6
7
$cookie = getMyCookie( ('name' => $name));
8
$uribase = (basename(str_replace( ('-', '.php'), '', $_SERVER[
9
10
if (is_object($cookie->sites->$uribase)) {
11
$cookie->sites->$uribase->url = $_SERVER["REQUEST_URI"];
12
$cookie->sites->$uribase->hits = ($cookie->sites->$uribase->hits + 1);
13
}
14
15
$args = ();
16
$agrs['name'] = $name;
17
$agrs['value'] = json_encode( ("totalvisits" => ($cookie->totalvisits + 1), "sites" => $cookie->sites));
18
$agrs['expire'] = (time() + (365 * 24 * 60 * 60 * 1000));
19
$agrs['path'] = "/";
20
$agrs['domain'] = "localhost";
21
$agrs['secure'] = false;
22
$agrs['httponly'] = false;
23
24
setMyCookie($agrs);
25
}
26
27
updateMyCookie("Visitor");
Check if cookie exists
After we set our cookie with setMyCookie we update our cookie with each call, but no more setMyCookie can be called. Therefore, we help ourselves with this function in which we check whether our cookie has already been set.
0
/**
1
* This function gets the cookie
2
* @param type $name
3
* @return type
4
*/
5
function hasMyCookie($name = '') {
6
return (isset($_COOKIE[
7
}
8
9
// Of course, if there is a cookie, you can use it dynamically now, for example by Put a hash provided IP address here so you have a relative unique user that you can associate with other data.
10
if (hasMyCookie("Visitor")) {
11
updateMyCookie("Visitor");
12
} else {
13
$args = ();
14
$args['name'] = 'Visitor';
15
$args['value'] = json_encode( ("totalvisits" => 0, "sites" => ''));
16
$args['expire'] = (time() + 2592000);
17
$args['path'] = "/";
18
$args['domain'] = "localhost";
19
$args['secure'] = false;
20
$args['httponly'] = false;
21
setMyCookie($args);
22
}
Remove cookie again
Of course you can also delete the cookie or all cookies. We can do this as follows.
0
/**
1
* This function delete the cookie by name
2
* @param type $name
3
*/
4
function deleteMyCookie($name = '') {
5
6
if ($name) {
7
unset($_COOKIE[
8
setcookie($name, null, -1, '/');
9
} else {
10
if (isset($_SERVER['HTTP_COOKIE'])) {
11
$cookies = (';', $_SERVER['HTTP_COOKIE']);
12
foreach ($cookies as $cookie) {
13
$parts = ('=', $cookie);
14
$remove = ($parts[0]);
15
if (unserialize($_COOKIE[$remove]) != false) {
16
unset($_COOKIE[$remove]);
17
}
18
}
19
}
20
}
21
}
22
23
// Call our function, otherwise nothing will happen if we do not call :)
24
deleteMyCookie("Visitor");
If we send a name with this then only this cookie will be removed, but we will call the function without a string so all cookies are removed which have a serialize string, so we do not touch other cookies.
A disadvantage or not?
The disadvantage, because we work on the server side, we can only track and record user interactions when refreshing the page. But that's why there is JavaScript and so we can read the same cookie and thus hold even more without having to reload the page each time. Even up to the mouse movement and which positions the user resides can be determined and much more. Here you can read this cookie we placed above JavaScript JavaScript - set and use cookies
Here is the whole code but in a class compiled and ready for use, you can change the name of the class and also rename the functions. Store your functions in classes and also separately in files so that you do not lose the overview as your project grows.
0
/**
1
* Description of Cookie
2
*
3
* @author Samet Tarim
4
* @copyright (c) 2018, Samet Tarim
5
* @package MelAbu
6
* @subpackage MB Tornado Ai
7
* @since 1.0
8
* @link http://tnado.com/
9
*/
10
class MyCookie {
11
12
/**
13
* This function set the cookie
14
* @param $agrs
15
*/
16
public function setMyCookie( $agrs = ()) {
17
$filename = '';
18
$linenum = '';
19
// Check if $args and header not sent
20
if ($agrs && !headers_sent($filename, $linenum)) {
21
// @see http://php.net/manual/de/function.setcookie.php
22
setcookie($agrs);
23
}
24
//.. is header sent or no args then do this
25
else {
26
// Check if header variables
27
if (isset($filename) && isset($linenum)) {
28
// Send error to admin or write in log file
29
'can not send cookie';
30
// trigger_error("Cookie could not be set on $filename line $linenum while header sent", E_USER_ERROR);
31
}
32
}
33
}
34
35
/**
36
* This function check if cookie exists
37
* @param type $name
38
* @return type
39
*/
40
public function hasMyCookie($name = '') {
41
return (isset($_COOKIE[
42
}
43
44
/**
45
* This function gets the cookie
46
* @param type $args
47
* @return type
48
*/
49
public function getMyCookie($args = ()) {
50
51
return (isset($args["name"]) && isset($_COOKIE[$args["name"]]) ? json_decode($_COOKIE[$args["name"]]) : $_COOKIE);
52
}
53
54
/**
55
* This function update the cookie by name
56
* @param type $name
57
* @return type
58
*/
59
public function updateMyCookie($name = '') {
60
61
$cookie = $this->getMyCookie( ('name' => $name));
62
$uribase = (basename(str_replace( ('-', '.php'), '', $_SERVER["REQUEST_URI"])), '/');
63
64
if (is_object($cookie->sites->$uribase)) {
65
$cookie->sites->$uribase->url = $_SERVER["REQUEST_URI"];
66
$cookie->sites->$uribase->hits = ($cookie->sites->$uribase->hits + 1);
67
}
68
69
$args = ();
70
$agrs['name'] = $name;
71
$agrs['value'] = json_encode( ("totalvisits" => ($cookie->totalvisits + 1), "sites" => $cookie->sites));
72
$agrs['expire'] = (time() + (365 * 24 * 60 * 60 * 1000));
73
$agrs['path'] = "/";
74
$agrs['domain'] = "localhost";
75
$agrs['secure'] = false;
76
$agrs['httponly'] = false;
77
78
$this->setMyCookie($agrs);
79
}
80
81
/**
82
* This function delete the cookie by name
83
* @param type $name
84
*/
85
public function deleteMyCookie($name = '') {
86
87
if ($name) {
88
unset($_COOKIE[$name]);
89
setcookie($name, null, -1, '/');
90
} else {
91
if (isset($_SERVER['HTTP_COOKIE'])) {
92
$cookies = (';', $_SERVER['HTTP_COOKIE']);
93
foreach ($cookies as $cookie) {
94
$parts = ('=', $cookie);
95
$remove = ($parts[0]);
96
if (unserialize($_COOKIE[$remove]) != false) {
97
unset($_COOKIE[$remove]);
98
}
99
}
100
}
101
}
102
}
103
104
}
So you use it as an object and it is much clearer;) You can of course set attributes with setter and getter and so create the arrays or send in outsourced etc ...
0
1
require_once './php/cookie.php';
2
$COOKIE = new MyCookie();
3
4
// Delete the cookie
5
// $COOKIE->deleteMyCookie("Visitor");
6
7
if ($COOKIE->hasMyCookie("Visitor")) {
8
$COOKIE->updateMyCookie("Visitor");
9
} else {
10
$args = ();
11
$args[
12
$args['value'] = json_encode( ("totalvisits" => 0, "sites" => ''));
13
$args['expire'] = (time() + (365 * 24 * 60 * 60 * 1000));
14
$args['path'] = "/";
15
$args['domain'] = "localhost";
16
$args['secure'] = false;
17
$args['httponly'] = false;
18
$COOKIE->setMyCookie($args);
19
}
20
21
<!DOCTYPE html>
22
<html>
23
<head>
24
25
<title>Cookies</title>
26
<link href="css/style.css" rel="stylesheet">
27
<script type="text/javascript" src="js/script.js"></script>
28
</head>
29
<body>
30
<div class="wrap">
31
<ul>
32
<li><a href="index.php">Home</a></li>
33
<li><a href="second.php">Second</a></li>
34
</ul>
35
36
// All cookies if this cookie does not exist or if function is called without parameter
37
// A specific cookie that we have set up with the name visitor
38
'<pre>';
39
var_dump($COOKIE->getMyCookie( ("name" => 'Visitor')));
40
'</pre>';
41
42
</div>
43
</body>
44
</html>
Advertising