Chapterبەش 10 · Lectureوانە 10.1
Cookiesکووکییەکان
How a website asks the browser to remember small pieces of text: create cookies with setcookie(), read them from $_COOKIE, choose their expiry time, delete them, understand third-party cookies, and keep cookies safe.
چۆن داوا لە دەکات پارچە دەقی بچووک لە بیر بگرێت: بە setcookie() دروست بکە، لە $_COOKIEـەوە بیانخوێنەوە، هەڵبژێرە، بیانسڕەوە، تێبگە و پارێزراو ڕابگرە.
What you will learnچی فێر دەبیت
- Explain what a cookie is and how it travels between the browser and the server.
- Create a cookie with
setcookie()and choose its expiry time, path, domain, Secure and HttpOnly settings. - Read cookies safely from
$_COOKIEand explain why a new cookie appears only on the next request. - Delete a cookie correctly.
- Explain third-party cookies and how to block cookies in a browser.
- Recognise what must never be stored in a cookie.
- ڕوونی بکەیتەوە چییە و چۆن لە نێوان و دەڕوات و دێتەوە.
- بە
setcookie()دروست بکەیت و ، ، دۆمەین، Secure و HttpOnlyـی بۆ هەڵبژێریت. - بە سەلامەتی لە
$_COOKIEـەوە بخوێنیتەوە و ڕوونی بکەیتەوە بۆچی نوێ تەنها لە داهاتوودا دەردەکەوێت. - بە دروستی بسڕیتەوە.
- ڕوون بکەیتەوە و بزانیت چۆن لە ڕابگیرێن.
- بزانیت چی هەرگیز نابێت لە خەزن بکرێت.
Why websites need cookiesبۆچی تۆڕگەکان پێویستیان بە کووکییەکان هەیە
Open a shop's website, choose Kurdish as your language, and go to the next page. How does the next page know your choice? , the language of the web, is : every reaches the as if it were the first one, and the server remembers nothing about earlier requests (see HTTP is stateless).
دوکانێک بکەرەوە، زمانی کوردی هەڵبژێرە و بچۆ بۆ لاپەڕەی دواتر. لاپەڕەی دواتر چۆن هەڵبژاردنەکەت دەزانێت؟ ، کە زمانی وێبە، : هەر وەک جاری یەکەم دەگاتە و هیچ شتێکی لە لە بیر نییە (بڕوانە HTTP بێدۆخە).
To remember things from one request to the next, websites use two tools. A keeps a small piece of text in the visitor's . A keeps the data on the server; it is the subject of the next lecture. This lecture is about cookies.
بۆ ئەوەی شتەکان لە بۆ دواتر لە بیر بگرن، دوو ئامراز بەکار دەهێنن. پارچە دەقێکی بچووک لە سەردانکەرەکەدا هەڵدەگرێت. لەسەر هەڵدەگرێت؛ ئەمە بابەتی وانەی داهاتووـە. ئەم وانەیە دەربارەی .
Think of a tea seller in the bazaar. He has hundreds of customers and cannot remember them all. So he gives you a small card and writes on it: “Aram – black tea, little sugar”. You keep the card in your pocket and show it every time you come to his stall. He reads it and knows you at once. A cookie is that card: the website writes it, the browser keeps it, and the browser shows it to the same website on every visit.
چایچییەک لە بازاڕ بهێنە بەرچاوی خۆت. سەدان کڕیاری هەیە و ناتوانێت هەموویانی لە بیر بێت. بۆیە کارتێکی بچووکت دەداتێ و لەسەری دەنووسێت: «ئارام – چای ڕەش، شەکری کەم». تۆ کارتەکە لە گیرفانتدا هەڵدەگریت و هەر جارێک دێیتە لای، نیشانی دەدەیت. ئەویش دەیخوێنێتەوە و دەستبەجێ دەتناسێتەوە. هەمان ئەو کارتەیە: دەینووسێت، هەڵیدەگرێت و لە هەموو سەردانێکدا نیشانی هەمان دەداتەوە.
Where the analogy stops workingسنووری ئەم نموونەیە
The browser shows the card automatically, and only to the website that wrote it. But the card is in the visitor's pocket: the visitor can read it and even change it. So a website must never trust a cookie for important facts, such as who the visitor is.
کارتەکە خۆکارانە نیشان دەدات و تەنها بەو کە نووسیویەتی. بەڵام کارتەکە لە گیرفانی سەردانکەرەکەدایە: دەتوانێت بیخوێنێتەوە و تەنانەت بیگۆڕێت. بۆیە هەرگیز نابێت بۆ زانیاریی گرنگ، وەک ئەوەی سەردانکەرەکە کێیە، متمانە بە بکات.
What a cookie isکووکی چییە
A small piece of text that a website asks the browser to save. The browser sends it back with every later to that site. PHP creates it with setcookie() and reads it from $_COOKIE.
پارچە دەقێکی بچووکە کە تۆڕگەیەک داوا لە دەکات خەزنی بکات. تۆڕگەڕەکە لەگەڵ هەر دواتر بۆ هەمان تۆڕگە دەینێرێتەوە. PHP بە setcookie() دروستی دەکات و لە $_COOKIE دەیخوێنێتەوە.
The course describes a cookie like this: a small file that the server puts on the user's computer. Each time the same computer asks for a page of that website with a browser, the browser sends the cookie back, so the website learns about the user's earlier activity.
کۆرسەکە بەم شێوەیە دەناسێنێت: بچووکە کە لەسەر دایدەنێت. هەر جارێک هەمان بە داوای لاپەڕەیەکی ئەو بکات، دەنێرێتەوە، بەم شێوەیە لە چالاکییە پێشووەکانی ئاگادار دەبێت.
In more exact words, a cookie is a small piece of text with a name and a value, for example user=Aram. It travels in four steps:
بە وتەیەکی وردتر، پارچە دەقێکی بچووکە کە ناوێک و هەیە، بۆ نموونە user=Aram. بە چوار هەنگاو دەڕوات و دێتەوە:
- The browser asks for a page. On the first visit it has no cookie for this website.
- PHP calls
setcookie(). This adds aSet-Cookieto the . - The browser saves the cookie, together with its and its other settings.
- On every later request to the same website, the browser sends the cookie back in a
Cookierequest header. PHP puts it into the$_COOKIEarray.
- داوای دەکات. لە یەکەم سەرداندا هیچ بۆ ئەم نییە.
- PHP
setcookie()بانگ دەکات. ئەمە بە ناویSet-Cookieبۆ زیاد دەکات. - لەگەڵ و ڕێکخستنەکانی تری خەزن دەکات.
- لە هەموو دواتردا بۆ هەمان ، لە بە ناوی
Cookieدەنێرێتەوە. PHP دەیخاتە ناو$_COOKIEـەوە.
setcookie() only adds a header to the response; the browser sends the cookie back with the next request.گەشتی . setcookie() تەنها بۆ زیاد دەکات؛ لەگەڵ داهاتوودا دەنێرێتەوە.CêITWhat a cookie isکووکی چییە
What cookies are used forکووکییەکان بۆ چی بەکار دێن؟
- Remembering that you are logged in (through a session ID; see the warning below).
- Remembering the items in a shopping cart.
- Remembering your preferences: language, colour theme, text size.
- Tracking which pages you visit, and showing advertisements that fit your interests (targeted advertising).
- لە بیرگرتنی ئەوەی کە چوویتەتە ژوورەوە (لە ڕێگەی ؛ خوارەوە ببینە).
- لە بیرگرتنی ئەو کاڵایانەی خستووتنە ناو سەبەتەی کڕینەوە.
- لە بیرگرتنی ئارەزووەکانت: زمان، ڕەنگی ڕووکار، قەبارەی نووسین.
- شوێنکەوتنی ئەو لاپەڕانەی سەردانیان دەکەیت و پیشاندانی ڕیکلامی گونجاو لەگەڵ حەزەکانت (ڕیکلامی ئامانجدار).
A cookie can hold only text (), and only about 4 KB (about 4000 characters). Browsers also limit how many cookies one website may keep. Big or complex data belongs in a session or a .
تەنها دەتوانێت دەق () هەڵبگرێت و تەنها نزیکەی 4 KB (نزیکەی ٤٠٠٠ پیت). هەروەها سنوور بۆ ژمارەی ئەو دادەنێن کە یەک دەتوانێت هەیبێت. زۆر یان ئاڵۆز جێگەی لە یان .
What a cookie isکووکی چییە
First-party and third-party cookiesکووکییەکانی لایەنی یەکەم و کووکییەکانی لایەنی سێیەم
A cookie set by the website in your address bar is a first-party cookie. But a web page can also contain parts from other websites: an advertisement, a “Like” button, a video player. When one of those other websites sets a cookie, it is a . It belongs to the other website, not to the site you are visiting.
ئەو کە ناو شریتی ناونیشانەکەت دایدەنێت، لایەنی یەکەمە. بەڵام دەتوانێت بەشی تریشی تێدا بێت: ڕیکلامێک، دوگمەیەکی «Like»، لێدەرێکی ڤیدیۆ. کاتێک یەکێک لەو تۆڕگانەی تر دادەنێت، ئەوە . هی ئەو ترەیە، نەک هی ئەو تۆڕگەیەی سەردانی دەکەیت.
The course slide shows how advertising companies use third-party cookies to follow you from site to site. This is called retargeting. Here is the idea, redrawn and corrected:
سلایدەکەی کۆرسەکە پیشان دەدات کە کۆمپانیاکانی ڕیکلام چۆن بەکار دەهێنن بۆ ئەوەی لە تۆڕگەیەکەوە بۆ تر بەدوات بکەون. پێی دەوترێت ڕیکلامی دووبارە-ئامانجگرتن (retargeting). بیرۆکەکە لێرەدایە، دووبارە کێشراوەتەوە و ڕاست کراوەتەوە:
id=77 belongs to ads.example, which is embedded in both websites.ڕیکلامی دووبارە-ئامانجگرتن بە . id=77 هی ads.exampleـە، کە لە هەردوو تۆڕگەکەدا دانراوە.CêIT- You visit shop A and look at shoes.
- Shop A's page contains an advertisement from ads.example. Your browser asks ads.example for it, and ads.example sets its own cookie,
id=77. - Later you visit news site B.
- Site B also shows advertisements from ads.example. Your browser sends ads.example its cookie
id=77. Now ads.example knows: “visitor 77 looked at shoes”, and it shows a shoe advertisement on B. - You click the advertisement and return to shop A.
- سەردانی فرۆشگای A دەکەیت و سەیری پێڵاو دەکەیت.
- لاپەڕەی فرۆشگای A ڕیکلامێکی ads.exampleی تێدایە. داوای لە ads.example دەکات و ads.example خۆی دادەنێت:
id=77. - دواتر سەردانی هەواڵی B دەکەیت.
- Bیش ڕیکلامی ads.example پیشان دەدات.
id=77بۆ ads.example دەنێرێت. ئێستا ads.example دەزانێت: «سەردانکەری ٧٧ سەیری پێڵاوی کردووە» و ڕیکلامی پێڵاو لەسەر B پیشان دەدات. - لە ڕیکلامەکە دەکەیت و دەگەڕێیتەوە بۆ فرۆشگای A.
Shows how a cookie travels between the browser and the server, and how third-party cookies let advertising companies follow you across many websites.
نیشان دەدات چۆن لە نێوان و دێت و دەچێت و چۆن ڕێگە دەدەن کۆمپانیاکانی ڕیکلام لە زۆر شوێنت بکەون.
Watch 1:39–5:25: how cookies work and how they track you.
لە 1:39 تا 5:25 سەیر بکە: چۆن کار دەکەن و چۆن شوێنت دەکەون.
What a cookie isکووکی چییە
Zombie cookies and supercookiesکووکییە زۆمبییەکان و سووپەرکووکییەکان
A keeps hidden copies in other corners of the browser and re-creates itself after you delete it. A keeps the same kind of ID somewhere else, for example in the browser's , so it is much harder to delete or block. Both are tracking tricks, not , and both make your longer: see Your digital footprint.
کۆپیی شاراوە لە گۆشەکانی تری هەڵدەگرێت و دوای ئەوەی دەیسڕیتەوە خۆی دووبارە دروست دەکاتەوە. هەمان جۆری لە شوێنێکی تر هەڵدەگرێت، بۆ نموونە لە ، بۆیە سڕینەوە یان ڕاگرتنی زۆر قورسترە. هەردووکیان فێڵی شوێنکەوتنن، نەک و هەردووکیان درێژتر دەکەن: بڕوانە شوێنپێ دیجیتاڵییەکەت.
What a cookie isکووکی چییە
How to block cookies in your browserچۆن کووکییەکان لە تۆڕگەڕەکەتدا ڕابگریت
You decide which cookies your browser accepts. The place is similar in every browser: open Settings (or Preferences), then Privacy and security, then Cookies. The exact names change a little from browser to browser. There you can:
تۆ بڕیار دەدەیت کام وەربگرێت. شوێنەکەی لە هەموو لە یەک دەچێت: Settings (یان Preferences) بکەرەوە، پاشان Privacy and security، پاشان Cookies. ناوەکان لە تۆڕگەڕێکەوە بۆ یەکێکی تر کەمێک دەگۆڕێن. لەوێ دەتوانیت:
- block third-party cookies only;
- block all cookies;
- delete all cookies every time you close the browser;
- see and delete the cookies of one website.
- تەنها ڕابگریت؛
- هەموو ڕابگریت؛
- هەر جارێک دادەخەیت هەموو بسڕیتەوە؛
- یەک ببینیت و بیانسڕیتەوە.
Browser extensions (add-ons) can also block or manage cookies.
دەتوانن ڕابگرن یان بەڕێوەیان ببەن.
Creating a cookie with setcookie()دروستکردنی کووکی بە setcookie()
To create a cookie, PHP has the setcookie(). It does not save anything by itself. It only adds a Set-Cookie header to the response, and the browser does the saving.
بۆ دروستکردنی ، PHP setcookie()ی هەیە. ئەم کردارە خۆی هیچ شتێک خەزن ناکات. تەنها سەردێڕی Set-Cookie بۆ زیاد دەکات و خەزنکردنەکە دەکات.
The course writes the syntax like this: setcookie(name, value, expire, path, domain, secure, httponly). In the PHP 8 manual the same function looks like this:
کۆرسەکە بەم شێوەیە دەنووسێت: setcookie(name, value, expire, path, domain, secure, httponly). لە ڕێبەری PHP 8دا هەمان بەم شێوەیەیە:
setcookie(string $name, string $value = "", int $expires_or_options = 0, string $path = "",
string $domain = "", bool $secure = false, bool $httponly = false): boolExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Seven . After
=you see the that PHP uses when you leave a parameter out. The third parameter is called$expires_or_optionsbecause it can also be an options array (see below); in this lecture we simply call itexpires. PHP's error messages use the long name.حەوت . دوای
=ئەو دەبینیت کە PHP بەکاری دەهێنێت ئەگەر پارامیتەرێکت دانەنا. سێیەم ناوی$expires_or_optionsـە، چونکە دەشتوانێت ڕێکخستن بێت (خوارەوە ببینە)؛ لەم وانەیەدا بە کورتی پێی دەڵێینexpires. پەیامەکانی PHP ناوە درێژەکە بەکار دەهێنن.- Lineدێڕی 2
The is
truewhen the header could be added,falsewhen it is too late (output already sent).trueـە کاتێک زیاد کرا وfalseـە کاتێک زۆر درەنگە ( پێشتر نێردراوە).
| Parameter | What it meansواتاکەی | Exampleنموونە | If you leave it outئەگەر دایننەنێیت |
|---|---|---|---|
name | The cookie's name. Use letters, digits and _. No spaces, =, , or ;.ناوی . پیت، ژمارە و _ بەکاربهێنە. ، =، , و ; قەدەغەن. | 'user' | requiredپێویستە |
value | The text to store (a string).ئەو دەقەی خەزن دەکرێت (). | 'Aram' | "" |
expires | When the cookie ends, as a Unix : seconds since 1 January 1970. 0 means “when the browser closes”.کاتێک بەسەر دەچێت، وەک Unix: چرکەکان لە ١ی کانوونی دووەمی ١٩٧٠ەوە. 0 واتە «کاتێک دادەخرێت». | time() + 3600 | 0 |
path | Only URLs that start with this receive the cookie. / means the whole website.تەنها ئەو URLانەی بەم دەست پێدەکەن وەردەگرن. / واتە هەموو . | '/' | the current folder ئێستا |
domain | The host name (and its subdomains) that receive the cookie. Empty means only the current host.ئەو ناوی خانەخوێیەی (و ژێردۆمەینەکانی) کە وەردەگرن. بەتاڵ واتە تەنها هەمان خانەخوێ. | 'example.com' | "" |
secure | true: send the cookie only over .true: تەنها لە ڕێگەی بنێرە. | true | false |
httponly | true: cannot read the cookie (document.cookie).true: ناتوانێت بخوێنێتەوە (document.cookie). | true | false |
Only the name is required. The course says that “the name and value parameters are enough, all others are optional”. In practice you always give a value, and usually an expiry time and the path / as well.
تەنها ناو پێویستە. کۆرسەکە دەڵێت « ناو و بەسن، هەموو ئەوانی تر ئارەزوومەندانەن». لە کاری ڕاستەقینەدا هەمیشە دەدەیت و زۆرجار و /یش.
PHP 8 code: why session_start() and setcookie() must come before any output ('headers already sent'), and how to set, read and delete cookies.
کۆدی 8: بۆچی session_start() و setcookie() دەبێت پێش هەر بێن ( headers already sent) و چۆن دابنێیت، بیخوێنیتەوە و بیسڕیتەوە.
Watch 9:19 to the end: cookies and the $_COOKIE superglobal in PHP 8.
لە 9:19 تا کۆتایی سەیر بکە: و $_COOKIE لە 8دا.
Creating a cookie with setcookie()دروستکردنی کووکی بە setcookie()
From setcookie() to the Set-Cookie headerلە setcookie()ـەوە بۆ سەردێڕی Set-Cookie
setcookie() to the Set-Cookie header: each argument becomes one part of the header.لە setcookie()ـەوە بۆ سەردێڕی Set-Cookie: هەر دەبێتە بەشێک لە .CêITCreating a cookie with setcookie()دروستکردنی کووکی بە setcookie()
Choosing the expiry timeهەڵبژاردنی کاتی بەسەرچوون
The function time() returns the current moment as a Unix : the number of seconds since 1 January 1970 (UTC). To make a cookie live for some time, add that many seconds to time(). PHP turns the number into the date format of the Set-Cookie header for you.
time() ساتی ئێستا وەک Unix دەگەڕێنێتەوە: ژمارەی چرکەکان لە ١ی کانوونی دووەمی ١٩٧٠ەوە (UTC). بۆ ئەوەی ماوەیەک بژی، ئەو ژمارە چرکەیە بخە سەر time(). PHP خۆی ژمارەکە دەگۆڕێت بۆ شێوەی بەرواری سەردێڕی Set-Cookie.
<?php
$now = time(); // seconds since 1 January 1970 (UTC)
echo "Now: $now<br>";
echo "One hour later: " . ($now + 3600) . "<br>";
echo "30 days later: " . date('Y-m-d H:i', $now + 86400 * 30);Now: 1792150486 One hour later: 1792154086 30 days later: 2026-11-15 11:34
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Now: 1792150486<br>One hour later: 1792154086<br>30 days later: 2026-11-15 11:34Your numbers will be different: they depend on the moment you run the script.
ژمارەکانی تۆ جیاواز دەبن: پەیوەستن بەو ساتەی کارپێدەکەیت.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
time()gives a big whole number that grows by 1 every second.time()گەورە دەدات کە هەموو چرکەیەک 1 زیاد دەکات.- Lineدێڕی 5
date()turns a timestamp back into a readable date.date()دەگەڕێنێتەوە بۆ بەروارێکی خوێندراو.
| How long?چەند؟ | Secondsچرکە | In PHPلە PHPدا |
|---|---|---|
| 1 minute١ خولەک | 60 | time() + 60 |
| 30 minutes٣٠ خولەک | 1800 | time() + 60 * 30 |
| 1 hour١ کاتژمێر | 3600 | time() + 3600 |
| 1 day١ ڕۆژ | 86400 | time() + 86400 |
| 1 week١ هەفتە | 604800 | time() + 7 * 24 * 60 * 60 |
| 30 days٣٠ ڕۆژ | 2592000 | time() + 86400 * 30 |
| when the browser closesکاتێک دادەخرێت | — | 0 |
With 0 (or with no expiry at all) the cookie is a session cookie: the browser deletes it when it closes. A time in the past tells the browser to delete the cookie now; that is how you delete a cookie.
بە 0 (یان بەبێ هیچ ) دەبێتە : کاتێک دادەخرێت دەیسڕێتەوە. کاتێکی ڕابردوو بە دەڵێت ئێستا بسڕەوە؛ ئەمە ڕێگای سڕینەوەی کووکییەکـە.
Creating a cookie with setcookie()دروستکردنی کووکی بە setcookie()
Secure, HttpOnly and SameSiteSecure، HttpOnly و SameSite
Secure. When secure is true, the browser sends the cookie only over an encrypted connection. When it is false, the cookie also travels over plain HTTP, where other people on the network may read it. On a real website with HTTPS, set it to true.
Secure. کاتێک secure بریتی بێت لە true، تەنها لە ڕێگەی پەیوەندییەکی شفرەکراوی دەنێرێت. کاتێک false بێت، بە HTTPـی سادەش دەڕوات، کە لەوێ کەسانی تری سەر دەتوانن بیخوێننەوە. لە ڕاستەقینە بە HTTPS، بیکە بە true.
A cookie option that stops from reading the cookie, so an attack cannot steal it. In PHP you set 'httponly' => true in the options array of setcookie().
بژاردەیەکی کووکییە کە ڕێگە نادات کووکییەکە بخوێنێتەوە، بۆیە هێرشی ناتوانێت بیدزێت. لە PHPـدا لە ڕیزەکی بژاردەکانی setcookie()دا 'httponly' => true دادەنرێت.
HttpOnly. When httponly is true, the cookie cannot be read or changed by code in the page (for example through document.cookie). The cookie is still sent with every HTTP request, so your PHP code reads it normally. It is “for the server only”.
HttpOnly. کاتێک httponly بریتی بێت لە true، کۆدی لە لاپەڕەکەدا ناتوانێت بخوێنێتەوە یان بیگۆڕێت (بۆ نموونە لە ڕێگەی document.cookie). هێشتا لەگەڵ هەموو HTTPدا دەنێردرێت، بۆیە کۆدی PHPـەکەت بە ئاسایی دەیخوێنێتەوە. تەنها «بۆ ».
Why does this help? In an attack, someone manages to run their own JavaScript in your page. With JavaScript they could steal the visitor's cookies, including the session ID, and use the visitor's account. HttpOnly stops that theft. It is not a complete defence against XSS: you still validate input and escape output with htmlspecialchars().
بۆچی ئەمە یارمەتی دەدات؟ لە هێرشێکی ، کەسێک دەتوانێت JavaScriptـی خۆی لە لاپەڕەکەتدا کارپێبکات. بە JavaScript دەتوانێت سەردانکەر بدزێت، لەوانە و سەردانکەرەکە بەکاربهێنێت. HttpOnly ڕێگە لەم دزینە دەگرێت. بەرگرییەکی تەواو نییە دژی XSS: هێشتا دەبێت پشتڕاست بکەیتەوە و بە htmlspecialchars() بپارێزیت.
Since PHP 7.3 you can also give the settings as an . This form is easier to read, and with setcookie() it is the only way to set SameSite:
لە PHP 7.3ـەوە دەتوانیت ڕێکخستنەکان وەک بدەیت. ئەم شێوەیە ئاسانتر دەخوێندرێتەوە و لەگەڵ setcookie()دا تاکە ڕێگایە بۆ دانانی SameSite:
<?php
setcookie('theme', 'dark', [
'expires' => time() + 7 * 24 * 60 * 60, // one week
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
echo "Theme saved.";Set-Cookie: theme=dark; expires=Fri, 23 Oct 2026 11:34:46 GMT; Max-Age=604800; path=/; secure; HttpOnly; SameSite=Lax Theme saved.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
expires: one week from now.expires: هەفتەیەک لە ئێستاوە.- Lineدێڕی 5-6
secureandhttponly: HTTPS only, hidden from JavaScript.secureوhttponly: تەنها HTTPS، شاراوە لە JavaScript.- Lineدێڕی 7
samesite:'Lax'is a good default (see below).samesite:'Lax'هەڵبژاردنێکی بنەڕەتیی باشە (خوارەوە ببینە).
Creating a cookie with setcookie()دروستکردنی کووکی بە setcookie()
setcookie() must come before any outputsetcookie() دەبێت پێش هەر دەرخستەیەک بێت
An HTTP response has two parts: first the headers, then the body (the HTML). PHP sends the headers at the moment your script produces its first output: the first echo, the first HTML outside <?php ?>, even one space or an empty line before <?php. After that, setcookie() is too late. PHP shows a , the function returns false, and no cookie is set:
HTTP دوو بەشی هەیە: سەرەتا ، پاشان ناوەڕۆک (HTMLـەکە). PHP سەردێڕەکان ئەو ساتە دەنێرێت کە یەکەم خۆی دروست دەکات: یەکەم echo، یەکەم HTML لە دەرەوەی <?php ?>، تەنانەت یەک یان دێڕێکی بەتاڵ پێش <?php. دوای ئەوە، setcookie() زۆر درەنگە. PHP پیشان دەدات، false دەگەڕێنێتەوە و هیچ دانانرێت:
<p>Hello</p>
<?php
$ok = setcookie("user", "Aram");
var_dump($ok);Hello Warning: Cannot modify header information - headers already sent by (output started at /www/too-late.php:1) in /www/too-late.php on line 3 bool(false)
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<p>Hello</p>
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /www/too-late.php:1) in <b>/www/too-late.php</b> on line <b>3</b><br />
bool(false)Run with output buffering off. The response contains no Set-Cookie header.
بە کوژاندنەوەی کارپێکراوە. هیچ سەردێڕێکی Set-Cookieـی تێدا نییە.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
HTML outside PHP is output. The headers leave here.
HTML لە دەرەوەی PHP . سەردێڕەکان لێرە دەڕۆن.
- Lineدێڕی 3
Too late: the
Set-Cookieheader cannot be added any more.زۆر درەنگە: ئیتر سەردێڕی
Set-Cookieزیاد ناکرێت.
setcookie(), session_start(), header()) must run before the first output.سەرەتا ، پاشان ناوەڕۆک. هەر شتێک بنێرێت (setcookie()، session_start()، header()) دەبێت پێش یەکەم کار بکات.CêITXAMPP's php.ini turns on (output_buffering = 4096). PHP then keeps the first 4096 bytes of output in a buffer and sends the headers later, so this mistake may go unnoticed on your computer and break on another server. The visit counter below is a real example. The same rule holds for header() (Redirects) and session_start() (Sessions).
php.iniـی XAMPP هەڵدەکات (output_buffering = 4096). ئەوکات PHP یەکەم ٤٠٩٦ ڕادەگرێت و سەردێڕەکان دواتر دەنێرێت، بۆیە لەوانەیە ئەم هەڵەیە لە کۆمپیوتەرەکەتدا هەست پێ نەکرێت و لەسەر تر تێک بچێت. ژمێرەری سەردانی خوارەوە نموونەیەکی ڕاستەقینەیە. هەمان یاسا بۆ header() (ئاڕاستەکردنەوەکان) و session_start() (سێشنەکان) ڕاستە.
Creating a cookie with setcookie()دروستکردنی کووکی بە setcookie()
Rules for names and valuesیاساکانی ناو و نرخ
A cookie name must not be empty, and it must not contain =, ,, ;, spaces, tabs or new lines. Use letters, digits and _, for example file_name or favourite_color. The value must be a ; numbers are turned into strings, but an is refused. PHP 8 stops with an when you break these rules:
ناوی نابێت بەتاڵ بێت و نابێت =، ,، ;، ، Tab یان دێڕی نوێی تێدا بێت. پیت، ژمارە و _ بەکاربهێنە، بۆ نموونە file_name یان favourite_color. دەبێت بێت؛ ژمارەکان دەگۆڕدرێن بۆ ، بەڵام وەرناگیرێت. ئەگەر ئەم یاسایانە بشکێنیت، PHP 8 بە دەوەستێت:
<?php
foreach ([['', 'x'], ['my cookie', 'x'], ['a=b', 'x']] as [$n, $v]) {
try { setcookie($n, $v); } catch (\Throwable $e) { echo get_class($e), ": ", $e->getMessage(), "\n"; }
}
try { setcookie('cart', ['tea', 'sugar']); } catch (\Throwable $e) { echo get_class($e), ": ", $e->getMessage(), "\n"; }ValueError: setcookie(): Argument #1 ($name) must not be empty ValueError: setcookie(): Argument #1 ($name) cannot contain "=", ",", ";", " ", "\t", "\r", "\n", "\013", or "\014" ValueError: setcookie(): Argument #1 ($name) cannot contain "=", ",", ";", " ", "\t", "\r", "\n", "\013", or "\014" TypeError: setcookie(): Argument #2 ($value) must be of type string, array given
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Three bad names: empty, with a space, with
=.سێ ناوی هەڵە: بەتاڵ، بە ، بە
=.- Lineدێڕی 5
An array as the value.
وەک .
PHP also encodes special characters in the value for you. A space becomes %20 in the header, and $_COOKIE decodes it again on the next request:
PHP هەروەها پیتە تایبەتەکانی ناو بۆت کۆد دەکات. لە دەبێتە %20 و $_COOKIE لە داهاتوودا دووبارە دەیکاتەوە بە :
<?php
setcookie("fullname", "Aram Ali", time() + 3600);
echo $_COOKIE["fullname"] ?? "(no cookie yet)";Request: Cookie: fullname=Aram%20Ali Response: Set-Cookie: fullname=Aram%20Ali; expires=…; Max-Age=3600 Aram Ali
Example 1: create a cookie and check itنموونەی ١: کووکییەک دروست بکە و بیپشکنە
This page creates a cookie named user with the value Aram. It lives for 30 days and belongs to the whole website (/). Then the page uses isset() to ask whether the browser sent a cookie with that name.
ئەم لاپەڕەیە بە ناوی user و Aram دروست دەکات. ٣٠ ڕۆژ دەژی و هی هەموو (/). پاشان لاپەڕەکە بە isset() دەپرسێت ئایا بەو ناوە ناردووە.
<?php
$cookie_name = "user";
$cookie_value = "Aram";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day in seconds
?>
<html>
<body>
<?php
if (!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . htmlspecialchars($_COOKIE[$cookie_name]);
}
?>
</body>
</html>Cookie named 'user' is not set!
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<html>
<body>
Cookie named 'user' is not set!</body>
</html>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
The name and the value in two .
ناو و لە دوو .
- Lineدێڕی 4
Create the cookie: 86400 seconds = 1 day, × 30 = 30 days. Path
/= the whole site. This line is before any HTML.دروست بکە: 86400 چرکە = ١ ڕۆژ، × 30 = ٣٠ ڕۆژ.
/= هەموو . ئەم دێڕە پێش هەموو HTMLێکە.- Lineدێڕی 9
isset()checks whether the browser sent the cookie with this request.isset()دەپشکنێت ئایا لەگەڵ ئەم ناردووە.- Lineدێڕی 13
htmlspecialchars(): a cookie comes from the visitor, so escape it before printing.htmlspecialchars(): لە سەردانکەرەوە دێت، بۆیە پێش چاپکردن بیپارێزە.
Cookie 'user' is set! Value is: Aram
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<html>
<body>
Cookie 'user' is set!<br>Value is: Aram</body>
</html>Why does the first visit say “not set”? Look at the HTTP messages. On the first request the browser has no cookie. setcookie() only puts a header into the response. The browser sends the cookie back from the second request on:
بۆچی یەکەم سەردان دەڵێت «not set»؟ سەیری نامەکانی HTTP بکە. لە یەکەم هیچ نییە. setcookie() تەنها دەخاتە ناو . لە دووەمەوە دەنێرێتەوە:
GET /example1.php HTTP/1.1
Host: localhost
HTTP/1.1 200 OK
Set-Cookie: user=Aram; expires=Sun, 15 Nov 2026 11:34:46 GMT; Max-Age=2592000; path=/
Content-Type: text/html; charset=UTF-8
GET /example1.php HTTP/1.1
Host: localhost
Cookie: user=AramExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-2
Request 1: no
Cookieheader.١: هیچ سەردێڕێکی
Cookieنییە.- Lineدێڕی 5
Response 1: PHP turned
time() + 86400 * 30into a date, and also wroteMax-Age(seconds to live).١: PHP
time() + 86400 * 30ی گۆڕی بۆ بەروار وMax-Ageـیشی نووسی (چرکەکانی ژیان).- Lineدێڕی 8-10
Request 2: the browser sends only
name=valueback, not the expiry or the path.٢: تەنها
name=valueدەنێرێتەوە، نەک و .
Example 1: create a cookie and check itنموونەی ١: کووکییەک دروست بکە و بیپشکنە
The original slide codeکۆدی ئەسڵیی سلایدەکە
Example 1: create a cookie and check itنموونەی ١: کووکییەک دروست بکە و بیپشکنە
Four rules to rememberچوار یاسا کە دەبێت لە بیرت بێت
The course lists what you need to know when you use cookies:
کۆرسەکە ئەوەی دەبێت بیزانیت کاتێک بەکار دەهێنیت، ڕیز دەکات:
- A cookie is not visible until the next page load.
$_COOKIEholds what the browser sent with this request. A cookie you create now is in the response, so you see it from the next request on. - Test a cookie on the next page load, before it expires. Reload the page (or open another page of the site) to check that the cookie was set.
- The expiry time is set with the
expiresparameter (the course calls it “expire”):time()plus a number of seconds. - Delete a cookie with the same parameters you used to set it: the same name, path and domain. See Deleting a cookie.
- تا بارکردنی داهاتووی لاپەڕەکە دەرناکەوێت.
$_COOKIEئەوەی تێدایە کە لەگەڵ ئەم ناردوویەتی. کە ئێستا دروستی دەکەیت لە ناو ، بۆیە لە داهاتووەوە دەیبینیت. - لە بارکردنی داهاتووی لاپەڕەکەدا تاقی بکەرەوە، پێش ئەوەی بەسەر بچێت. لاپەڕەکە نوێ بکەرەوە (یان لاپەڕەیەکی تری بکەرەوە) بۆ ئەوەی بزانیت دانراوە.
- بە
expiresدادەنرێت (کۆرسەکە پێی دەڵێت «expire»):time()لەگەڵ ژمارەیەک چرکە. - بەو بسڕەوە کە پێیان دروستت کرد: هەمان ناو، و دۆمەین. سڕینەوەی کووکی ببینە.
Example 2: all seven parametersنموونەی ٢: هەر حەوت پارامیتەرەکە
The second course example stores every parameter in its own variable, so you can see them all. This is the original code from the slide:
نموونەی دووەمی کۆرسەکە هەر لە تایبەتی خۆیدا هەڵدەگرێت، بۆ ئەوەی هەموویان ببینیت. ئەمە کۆدی ئەسڵیی سلایدەکەیە:
<?php /*Creating cokies file*/
$name = 'file name';
$value ='value ';
time();
//This function gives the current time in seconds, and here we use 60 seconds * 30 = 30 minutes?
// And therefore the cookie will expire in 30 minutes?
// You may have noticed that the completion time here has been allocated in seconds?
// PHP Language are converting the time to the right time formula automatically
$expireDate = time() + 60 * 30;
$path = '/example2/';
$domain = 'test.domain.com';
$secure = false;
// This variable is required to send the cookies file just in case there is a https connection.
$httponly = true;
// This variable is required to activate and send only the cookies file in case there is a http connection.
setcookie( $name, $value, $expireDate, $path, $domain, $secure, $httponly);
//.... We put the rest of the contents of the page here
?>Fatal error: Uncaught ValueError: setcookie(): Argument #1 ($name) cannot contain "=", ",", ";", " ", "\t", "\r", "\n", "\013", or "\014" in /www/example2.php:19
Stack trace:
#0 /www/example2.php(19): setcookie('file name', 'value ', 1792153762, '/example2/', 'test.domain.com', false, true)
#1 {main}
thrown in /www/example2.php on line 19HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<br />
<b>Fatal error</b>: Uncaught ValueError: setcookie(): Argument #1 ($name) cannot contain "=", ",", ";", " ", "\t", "\r", "\n", "\013", or "\014" in /www/example2.php:19
Stack trace:
#0 /www/example2.php(19): setcookie('file name', 'value ', 1792153762, '/example2/', 'test.domain.com', false, true)
#1 {main}
thrown in <b>/www/example2.php</b> on line <b>19</b><br />PHP 8 refuses the name 'file name' because it contains a space.
PHP 8 ناوی 'file name' ڕەت دەکاتەوە چونکە تێدایە.
Here is the corrected version. It runs, and you can see each parameter turn into a part of the header:
ئەمە وەشانە ڕاستکراوەکەیە. کار دەکات و دەبینیت هەر دەبێتە بەشێک لە :
<?php
// Creating a cookie with all seven parameters
$name = 'file_name'; // a cookie name may not contain spaces
$value = 'value';
$expires = time() + 60 * 30; // time() = now in seconds; 60 * 30 = 1800 seconds = 30 minutes
$path = '/example2/'; // the cookie is sent only to URLs that start with /example2/
$domain = 'test.domain.com'; // the cookie belongs to this host name
$secure = false; // true = send the cookie only over HTTPS
$httponly = true; // true = JavaScript cannot read the cookie
setcookie($name, $value, $expires, $path, $domain, $secure, $httponly);
// ... the rest of the page goes here
?>Set-Cookie: file_name=value; expires=Fri, 16 Oct 2026 12:04:46 GMT; Max-Age=1800; path=/example2/; domain=test.domain.com; HttpOnly
There is no secure in the header, because $secure is false.
هیچ secureێک لە سەردێڕەکەدا نییە، چونکە $secure بریتییە لە false.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
60 × 30 = 1800 seconds = 30 minutes.
60 × 30 = 1800 چرکە = ٣٠ خولەک.
- Lineدێڕی 6
Sent only to URLs under
/example2/.تەنها بۆ ئەو URLانە دەنێردرێت کە لە ژێر
/example2/دان.- Lineدێڕی 11
All seven arguments, in the order of the syntax.
هەر حەوت ، بە ڕیزبەندیی .
Reading cookies with $_COOKIEخوێندنەوەی کووکییەکان بە $_COOKIE
PHP puts every cookie that the browser sent into the $_COOKIE. It is an : the is the cookie's name and the value is the cookie's value. Like every superglobal, it works everywhere in your script (Superglobals).
PHP هەموو ئەو ناردوونی، دەخاتە ناو $_COOKIEـەوە. : ناوی و . وەک هەموو ، لە هەموو شوێنێکی کار دەکات (سووپەرگلۆباڵەکان).
<?php
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";Array
(
[user] => Aram
)HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<pre>Array
(
[user] => Aram
)
</pre>After Example 1 has set the cookie.
دوای ئەوەی نموونەی ١ دانا.
To read one cookie, use its name as the key. The course's “example3.php” does that, but it forgets one thing:
بۆ خوێندنەوەی یەک ، ناوەکەی وەک بەکاربهێنە. «example3.php»ی کۆرسەکە ئەمە دەکات، بەڵام شتێکی لە بیر دەچێت:
<html >
<head>
<title>PHP Script</title>
</head>
<body>
<?php
//Cookie: example3.php
$strCookieData = $_COOKIE[$cookie_name];
echo "<p>$strCookieData</p>";
?>
</body>
</html>Warning: Undefined variable $cookie_name in /www/example3.php on line 9 Deprecated: Using null as an array offset is deprecated, use an empty string instead in /www/example3.php on line 9 Warning: Undefined array key "" in /www/example3.php on line 9
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<html >
<head>
<title>PHP Script</title>
</head>
<body>
<br />
<b>Warning</b>: Undefined variable $cookie_name in <b>/www/example3.php</b> on line <b>9</b><br />
<br />
<b>Deprecated</b>: Using null as an array offset is deprecated, use an empty string instead in <b>/www/example3.php</b> on line <b>9</b><br />
<br />
<b>Warning</b>: Undefined array key "" in <b>/www/example3.php</b> on line <b>9</b><br />
<p></p></body>
</html><html>
<head>
<title>PHP Script</title>
</head>
<body>
<?php
// Cookie: example3.php
$cookie_name = "user";
if (isset($_COOKIE[$cookie_name])) {
$strCookieData = $_COOKIE[$cookie_name];
echo "<p>" . htmlspecialchars($strCookieData) . "</p>";
} else {
echo "<p>There is no cookie named '$cookie_name' yet.</p>";
}
?>
</body>
</html>Aram
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<html>
<head>
<title>PHP Script</title>
</head>
<body>
<p>Aram</p></body>
</html>With no cookie the page says: There is no cookie named 'user' yet.
بەبێ لاپەڕەکە دەڵێت: There is no cookie named 'user' yet.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 8
The name is defined in this file.
ناوەکە لەم فایلەدا پێناسە کراوە.
- Lineدێڕی 9
isset()first: no warning when the cookie is missing.سەرەتا
isset(): کاتێک نییە هیچ نییە.- Lineدێڕی 11
Escape the value: the visitor controls it.
بپارێزە: سەردانکەر کۆنترۆڵی دەکات.
Reading cookies with $_COOKIEخوێندنەوەی کووکییەکان بە $_COOKIE
Reading a cookie right after setting itخوێندنەوەی کووکی ڕاستەوخۆ دوای دانانی
The course's PHP deck shows the shortest possible example: create a cookie and print it at once. On the first visit this does not work, because of rule 1:
سلایدەکانی PHPـی کۆرسەکە کورتترین نموونە پیشان دەدەن: دروست بکە و دەستبەجێ چاپی بکە. لە یەکەم سەرداندا ئەمە کار ناکات، لەبەر یاسای ١:
<?php
setcookie("user", "Aram", time() + 3600); // expires in one hour
echo $_COOKIE["user"];Warning: Undefined array key "user" in /www/deck.php on line 3
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<br />
<b>Warning</b>: Undefined array key "user" in <b>/www/deck.php</b> on line <b>3</b><br />On the second visit it prints Aram.
لە سەردانی دووەمدا Aram چاپ دەکات.
The ?? gives a default value when the key does not exist, without a warning:
?? کاتێک بوونی نییە دەدات، بەبێ :
<?php
setcookie("user", "Aram", time() + 3600); // expires in one hour
echo $_COOKIE["user"] ?? "No cookie yet. Reload the page.";No cookie yet. Reload the page.
Second visit: Aram
سەردانی دووەم: Aram
Deleting a cookieسڕینەوەی کووکی
PHP has no “delete cookie” function. Instead, you call setcookie() again with the same name, path and domain, an empty value, and an expiry time in the past. The browser sees that the cookie has expired and removes it.
PHP هیچ «سڕینەوەی »ی نییە. لە جیاتی ئەوە، جارێکی تر setcookie() بانگ دەکەیت بە هەمان ناو، و دۆمەین، بەتاڵ و لە ڕابردوودا. دەبینێت بەسەرچووە و لایدەبات.
<?php
// Same name and path as when the cookie was created, an empty value, and a time in the past
setcookie("user", "", time() - 3600, "/");
echo "The cookie 'user' has been deleted.";Set-Cookie: user=deleted; expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=0; path=/ The cookie 'user' has been deleted.
PHP writes the value “deleted” and a date in 1970 itself. On the next visit, Example 1 says again: Cookie named 'user' is not set!
PHP خۆی «deleted» و بەروارێک لە ١٩٧٠ دەنووسێت. لە سەردانی داهاتوودا، نموونەی ١ دیسان دەڵێت: Cookie named 'user' is not set!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
time() - 3600= one hour ago. The path/matches Example 1.time() - 3600= یەک کاتژمێر لەمەوبەر./لەگەڵ نموونەی ١ یەک دەگرێتەوە.
The login lab deletes its cookie the same way when the user logs out; see the cookie version of the login.
تاقیگەی کاتێک دەچێتە دەرەوە، خۆی بە هەمان شێوە دەسڕێتەوە؛ وەشانی کووکیی چوونەژوورەوە ببینە.
Two practical examples from the courseدوو نموونەی پراکتیکی لە کۆرسەکەوە
Students in this course wrote these two small programs in the lab. Both work on XAMPP, and both hide a lesson about cookies.
خوێندکارانی ئەم کۆرسە ئەم دوو بچووکەیان لە تاقیگەدا نووسی. هەردووکیان لەسەر XAMPP کار دەکەن و هەردووکیان وانەیەکیان دەربارەی تێدا شاراوەتەوە.
Two practical examples from the courseدوو نموونەی پراکتیکی لە کۆرسەکەوە
A visit counterژمێرەرێکی سەردان
This page counts how many times you opened it. The first part is an older session version, switched off with comments. The second part does the work with a cookie that lives for 5 seconds.
ئەم لاپەڕەیە دەژمێرێت چەند جار کردووتەتەوە. بەشی یەکەم وەشانێکی کۆنی کە بە ناچالاک کراوە. بەشی دووەم کارەکە بە دەکات کە ٥ چرکە دەژی.
<?php
// session_start();
// if (!$_SESSION["intCount"])
// {
// $_SESSION["intCount"] = 1;
// } else {
// $_SESSION["intCount"]++;
// }
// if ($_SESSION["intCount"] == null)
// {
// $_SESSION["intCount"] = 1;
// }
?>
<!-- <html>
<body>
<?php
//echo "You have accessed this page ".$_SESSION["intCount"]." times.";
?>
</body>
</html> -->
<?php
if (isset($_COOKIE["intCount"])) {
$count = $_COOKIE["intCount"];
$count++;
} else {
$count = 0;
}
setcookie("intCount", $count, time() + 5);
?>
<html>
<body>
<?php
echo "You have accessed this page " . $count . " times.";
?>
</body>
</html>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-14
The session version, all commented out. Its
!$_SESSION["intCount"]test gives a warning on the first visit; see the session counter.وەشانی ، هەمووی کراوە بە . تاقیکردنەوەی
!$_SESSION["intCount"]ی لە یەکەم سەرداندا دەدات؛ ژمێرەری سێشن ببینە.- Lineدێڕی 16-23
An HTML comment. The browser hides it, but it is still output sent by the server, and the PHP inside it still runs on the server.
HTML. دەیشارێتەوە، بەڵام هێشتا کە دەینێرێت و PHPـی ناوی هێشتا لەسەر کار دەکات.
- Lineدێڕی 26-31
Read the old count, or start at 0.
ژمارەی کۆن بخوێنەوە، یان لە 0ـەوە دەست پێبکە.
- Lineدێڕی 33
Save the count for 5 seconds. This line comes after the output on lines 16-23.
ژمارەکە بۆ ٥ چرکە خەزن بکە. ئەم دێڕە دوای دێڕەکانی 16-23 دێت.
| Visitسەردان | Server without output buffering بەبێ | XAMPP (output_buffering = 4096)لە XAMPPدا (output_buffering = 4096) |
|---|---|---|
| 1 | Warning: headers already sent … 0 times: headers already sent … 0 times | You have accessed this page 0 times. |
| 2 | the same warning … 0 timesهەمان … 0 times | You have accessed this page 1 times. |
| 3 | the same warning … 0 timesهەمان … 0 times | You have accessed this page 2 times. |
| after a pause of more than 5 sدوای وەستانێکی زیاتر لە ٥ چرکە | … 0 times. | You have accessed this page 0 times. |
Warning: Cannot modify header information - headers already sent by (output started at /www/index.php:22) in /www/index.php on line 33 You have accessed this page 0 times.
The corrected counterژمێرەرە ڕاستکراوەکە
<?php
// Read the old count (0 if the browser sent no cookie), then add 1 for this visit
$count = (int) ($_COOKIE["intCount"] ?? 0);
$count++;
// Save the new count for 30 days. setcookie() must run before any HTML is sent.
setcookie("intCount", $count, time() + 30 * 24 * 60 * 60);
?>
<html>
<body>
<?php
$word = ($count === 1) ? "time" : "times";
echo "You have accessed this page $count $word.";
?>
</body>
</html>You have accessed this page 1 time. You have accessed this page 2 times. You have accessed this page 3 times.
If someone edits the cookie to intCount=abc, the next visit says: 1 time.
ئەگەر کەسێک بکات بە intCount=abc، سەردانی داهاتوو دەڵێت: 1 time.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
?? 0: no warning on the first visit.(int): a changed cookie such asabcbecomes 0.?? 0: لە یەکەم سەرداندا هیچ نییە.(int): دەستکاریکراو وەکabcدەبێتە 0.- Lineدێڕی 4
Add this visit, so the first visit counts as 1.
ئەم سەردانە زیاد بکە، بۆ ئەوەی یەکەم سەردان بە 1 بژمێردرێت.
- Lineدێڕی 7
30 days instead of 5 seconds, and before any HTML.
٣٠ ڕۆژ لە جیاتی ٥ چرکە و پێش هەموو HTMLێک.
- Lineدێڕی 12
“1 time”, “2 times”: the right word for each number.
«1 time»، «2 times»: وشەی گونجاو بۆ هەر ژمارەیەک.
Do you doubt that PHP inside an HTML comment runs? Try it:
گومانت هەیە کە PHP لە ناو HTMLدا کار دەکات؟ تاقی بکەرەوە:
<!-- <?php echo "PHP still runs here"; ?> -->
<p>Visible text</p>Visible text
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<!-- PHP still runs here -->
<p>Visible text</p>The browser shows only “Visible text”, but View Source shows that PHP ran inside the comment.
تەنها «Visible text» پیشان دەدات، بەڵام View Source پیشان دەدات کە PHP لە ناو لێدوانەکەدا کاری کردووە.
Two practical examples from the courseدوو نموونەی پراکتیکی لە کۆرسەکەوە
Saving the visitor’s languageخەزنکردنی زمانی سەردانکەر
This page lets the visitor choose a language from a . The choice is saved in a cookie named language, and the page greets the visitor in that language.
ئەم لاپەڕەیە ڕێگە بە سەردانکەر دەدات زمانێک لە هەڵبژێرێت. هەڵبژاردنەکە لە بە ناوی language خەزن دەکرێت و لاپەڕەکە بەو زمانە بەخێرهاتنی سەردانکەر دەکات.
<?php
// Check if the form has been submitted
if (isset($_POST['language'])) {
// Set the cookie to expire in 1 week (604800 seconds)
setcookie('language', $_POST['language'], time() + 10);
echo '<p>Your language preference has been saved!</p>';
}
$selectedLan = null;
// Check if the language cookie is set
if (isset($_COOKIE['language'])) {
// Display a message based on the selected language
switch ($_COOKIE['language']) {
case 'en':
echo '<p>Hello! Welcome to our website.</p>';
$selectedLan = "en";
break;
case 'fr':
echo '<p>Bonjour! Bienvenue sur notre site web.</p>';
$selectedLan = "fr";
break;
case 'es':
echo '<p>¡Hola! Bienvenido a nuestro sitio web.</p>';
$selectedLan = "es";
break;
case 'de':
echo '<p>Hallo! Willkommen auf unserer Webseite.</p>';
$selectedLan = "de";
break;
default:
echo '<p>Hello! Welcome to our website.</p>';
$selectedLan = "en";
break;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Language Preference</title>
</head>
<body>
<h1>Language Preference</h1>
<form method="post">
Select your preferred language:
<select name="language">
<option <?php if ($selectedLan == "en")
echo "selected"; ?> value="en">English</option>
<option <?php if ($selectedLan == "fr")
echo "selected"; ?> value="fr">Français</option>
<option <?php if ($selectedLan == "es")
echo "selected"; ?> value="es">Español</option>
<option <?php if ($selectedLan == "de")
echo "selected"; ?> value="de">Deutsch</option>
</select>
<button type="submit">Save Preference</button>
</form>
</body>
</html>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
The comment says one week, but the code says
time() + 10: ten seconds.دەڵێت یەک هەفتە، بەڵام کۆدەکە دەڵێت
time() + 10: دە چرکە.- Lineدێڕی 6
This message is echoed before
<!DOCTYPE html>, outside the HTML page.ئەم پەیامە پێش
<!DOCTYPE html>چاپ دەکرێت، لە دەرەوەی لاپەڕەی HTML.- Lineدێڕی 11
Reads
$_COOKIE: the value the browser sent with this request.$_COOKIEدەخوێنێتەوە: ئەو نرخەی لەگەڵ ئەم داواکارییەدا ناردوویەتی.- Lineدێڕی 50-57
A sticky : the saved language gets
selected.لکاو: زمانە خەزنکراوەکە
selectedوەردەگرێت.
Run it and watch what the visitor sees, step by step (verified with PHP 8.5):
کاری پێبکە و هەنگاو بە هەنگاو سەیری ئەوە بکە کە سەردانکەر دەیبینێت (بە PHP 8.5 پشتڕاست کراوەتەوە):
| Stepهەنگاو | The visitor…سەردانکەر… | Cookie sent with the requestئەو کووکییەی لەگەڵ داواکارییەکەدا نێردرا | The page showsلاپەڕەکە پیشان دەدات |
|---|---|---|---|
| 1 | opens the pageلاپەڕەکە دەکاتەوە | noneهیچ | only the formتەنها |
| 2 | chooses Français and presses SaveFrançais هەڵدەبژێرێت و Save دادەگرێت | noneهیچ | “saved!”, but no greeting, and the list still shows English«saved!»، بەڵام هیچ بەخێرهاتنێک نییە و لیستەکە هێشتا English پیشان دەدات |
| 3 | reloads within 10 secondsلە ماوەی ١٠ چرکەدا نوێی دەکاتەوە | language=fr | “Bonjour! …”, Français selected«Bonjour! …»، Français هەڵبژێردراوە |
| 4 | chooses Deutsch and presses SaveDeutsch هەڵدەبژێرێت و Save دادەگرێت | language=fr | “saved!”, but still “Bonjour!” and Français«saved!»، بەڵام هێشتا «Bonjour!» و Français |
| 5 | comes back after 10 secondsدوای ١٠ چرکە دەگەڕێتەوە | none (expired)هیچ (بەسەرچووە) | only the form: the choice is forgottenتەنها : هەڵبژاردنەکە لە بیر چووەتەوە |
Why is the new choice not visible at once?
بۆچی هەڵبژاردنە نوێیەکە دەستبەجێ دەرناکەوێت؟
In step 2 the browser sends the form, but it has no cookie yet. PHP runs setcookie(), which only puts a Set-Cookie header into the response. Then the page reads $_COOKIE['language'], and $_COOKIE holds what the browser sent with this request: nothing. In step 4 it holds the old value fr. The new value arrives only with the next request. This is rule 1, and the round-trip figure shows it.
لە هەنگاوی ٢دا دەنێرێت، بەڵام هێشتا هیچ نییە. PHP setcookie() کارپێدەکات، کە تەنها سەردێڕی Set-Cookie دەخاتە ناو . پاشان لاپەڕەکە $_COOKIE['language'] دەخوێنێتەوە و $_COOKIE ئەوەی تێدایە کە لەگەڵ ئەم ناردوویەتی: هیچ. لە هەنگاوی ٤دا نرخە کۆنەکەی fr تێدایە. نرخە نوێیەکە تەنها لەگەڵ داهاتوودا دەگات. ئەمە یاسای ١ـە و وێنەی گەشتی کووکی پیشانی دەدات.
10 seconds or one week?
١٠ چرکە یان یەک هەفتە؟
The comment promises one week (604800 seconds), but the code says time() + 10. So the cookie dies after ten seconds and the visitor's choice is lost (step 5). Probably the author used 10 seconds for testing and forgot to change it back. One week is time() + 604800, or more readable, time() + 7 * 24 * 60 * 60.
بەڵێنی یەک هەفتە دەدات (604800 چرکە)، بەڵام کۆدەکە دەڵێت time() + 10. بۆیە دوای دە چرکە دەمرێت و هەڵبژاردنی سەردانکەر لە دەست دەچێت (هەنگاوی ٥). لەوانەیە نووسەرەکە ١٠ چرکەی بۆ تاقیکردنەوە بەکار هێنابێت و لە بیری چووبێت بیگەڕێنێتەوە. یەک هەفتە بریتییە لە time() + 604800، یان بە شێوەیەکی خوێندراوتر time() + 7 * 24 * 60 * 60.
Fixing the language pageڕاستکردنەوەی لاپەڕەی زمان
<?php
$greetings = [
'en' => 'Hello! Welcome to our website.',
'fr' => 'Bonjour! Bienvenue sur notre site web.',
'es' => '¡Hola! Bienvenido a nuestro sitio web.',
'de' => 'Hallo! Willkommen auf unserer Webseite.',
];
$names = ['en' => 'English', 'fr' => 'Français', 'es' => 'Español', 'de' => 'Deutsch'];
$saved = false;
if (isset($_POST['language']) && isset($greetings[$_POST['language']])) {
// 1 week = 7 days x 24 hours x 60 minutes x 60 seconds = 604800 seconds
setcookie('language', $_POST['language'], time() + 7 * 24 * 60 * 60);
// $_COOKIE still holds the OLD value in this request, so use the new choice directly
$selectedLan = $_POST['language'];
$saved = true;
} else {
$selectedLan = $_COOKIE['language'] ?? 'en';
if (!isset($greetings[$selectedLan])) {
$selectedLan = 'en'; // unknown value (the user may have edited the cookie)
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Language Preference</title>
</head>
<body>
<h1>Language Preference</h1>
<?php if ($saved) echo '<p>Your language preference has been saved!</p>'; ?>
<p><?php echo $greetings[$selectedLan]; ?></p>
<form method="post">
Select your preferred language:
<select name="language">
<?php foreach ($names as $code => $name): ?>
<option value="<?php echo $code; ?>" <?php if ($code === $selectedLan) echo 'selected'; ?>><?php echo $name; ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Save Preference</button>
</form>
</body>
</html>Language Preference Your language preference has been saved! Bonjour! Bienvenue sur notre site web. Select your preferred language: [Français ▾] [Save Preference]
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<!DOCTYPE html>
<html>
<head>
<title>Language Preference</title>
</head>
<body>
<h1>Language Preference</h1>
<p>Your language preference has been saved!</p> <p>Bonjour! Bienvenue sur notre site web.</p>
<form method="post">
Select your preferred language:
<select name="language">
<option value="en" >English</option>
<option value="fr" selected>Français</option>
<option value="es" >Español</option>
<option value="de" >Deutsch</option>
</select>
<button type="submit">Save Preference</button>
</form>
</body>
</html>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-7
One array of greetings replaces the
switch; its keys are the allowed codes.یەک بەخێرهاتن جێگەی
switchدەگرێتەوە؛ ئەو کۆدانەن کە ڕێگەپێدراون.- Lineدێڕی 11
Only a known code is accepted.
تەنها کۆدێکی ناسراو وەردەگیرێت.
- Lineدێڕی 13
One week, computed in the code.
یەک هەفتە، لە کۆدەکەدا حیسابکراو.
- Lineدێڕی 15
Use the posted value now:
$_COOKIEstill has the old one in this request.ئێستا نێردراوەکە بەکاربهێنە:
$_COOKIEلەم داواکارییەدا هێشتا نرخە کۆنەکەی تێدایە.- Lineدێڕی 18-21
No post: read the cookie, and fall back to English for unknown values.
هیچ شتێک نەنێردراوە: بخوێنەوە و بۆ نەناسراو بگەڕێوە بۆ ئینگلیزی.
What never to put in a cookieچی هەرگیز نابێت بخرێتە ناو کووکییەوە
Cookies live on the visitor's computer. The visitor can read them, change them and invent new ones with the developer tools, and any program can send any Cookie header. So treat every cookie as :
لەسەر سەردانکەر دەژین. سەردانکەر دەتوانێت بە ئامرازەکانی پەرەپێدەر بیانخوێنێتەوە، بیانگۆڕێت و نوێ دروست بکات و هەر دەتوانێت هەر سەردێڕێکی Cookie بنێرێت. بۆیە هەموو وەک مامەڵە بکە:
- Never store a password in a cookie, not even a hashed one.
- Never use a cookie as proof of identity.
logged_in=yesoruser_id=7can be typed by anyone. Use a session; it keeps only a random ID in the cookie (login lecture). - Never trust prices, roles or permissions from a cookie, such as
role=adminorprice=1000. - Check and escape every cookie value: accept only expected values, and use
htmlspecialchars()before printing. - Keep cookies small (about 4 KB at most) and use few of them.
- Use
httponlyandsecurefor anything that matters, on an HTTPS website.
- هەرگیز لە خەزن مەکە، تەنانەت هاشکراویشی.
- هەرگیز وەک بەڵگەی ناسنامە بەکار مەهێنە.
logged_in=yesیانuser_id=7هەر کەسێک دەتوانێت بینووسێت. بەکاربهێنە؛ تەنها ناسێنەرێکی هەڕەمەکی لە هەڵدەگرێت (وانەی چوونەژوورەوە). - هەرگیز متمانە بە نرخی کاڵا، ڕۆڵ یان مەکە کە لە دێن، وەک
role=adminیانprice=1000. - هەموو بپشکنە و بیپارێزە: تەنها چاوەڕوانکراو وەربگرە و پێش چاپکردن
htmlspecialchars()بەکاربهێنە. - بچووک ڕابگرە (زۆرترین نزیکەی 4 KB) و کەمیان بەکاربهێنە.
httponlyوsecureبەکاربهێنە بۆ هەر شتێک کە گرنگە، لەسەر HTTPS.
That is the website's side. On the visitor's side, cookies are one part of the trail people leave online; where it is kept and how to clear it is in Where your footprints are kept.
ئەمە لایەنی . لە لایەنی سەردانکەرەوە، بەشێکن لەو شوێنپێیەی خەڵک لە ئینتەرنێتدا جێی دەهێڵن؛ لە کوێ هەڵدەگیرێت و چۆن دەسڕدرێتەوە لە شوێنپێکانت لە کوێ هەڵدەگیرێن ڕوون کراوەتەوە.
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوودەدات | Fixچارەسەر |
|---|---|---|
HTML, a space or echo before setcookie()HTML، یان echo پێش setcookie() | Warning “headers already sent”; no cookie (hidden on XAMPP by output buffering) «headers already sent»؛ هیچ نییە (لە XAMPPدا بە دەشاردرێتەوە) | Call setcookie() at the very topsetcookie() لە سەرەتای بانگ بکە |
Reading the cookie right after setcookie()خوێندنەوەی ڕاستەوخۆ دوای setcookie() | Empty or old value until the next request بەتاڵ یان کۆن تا داهاتوو | Use the value you just set; or redirectئەو نرخە بەکاربهێنە کە ئێستا دانات؛ یان ئاڕاستە بکەرەوە |
expires as a date string, e.g. "2026-12-31"expires وەک دەقی بەروار، بۆ نموونە "2026-12-31" | TypeError: the page stopsTypeError: لاپەڕەکە دەوەستێت | time() + seconds |
expires as plain seconds, e.g. 3600expires وەک چرکەی سادە، بۆ نموونە 3600 | A date in 1970: the cookie is deleted at onceبەروارێک لە ١٩٧٠: دەستبەجێ دەسڕدرێتەوە | time() + 3600 |
A comment that says one week, code that says time() + 10 کە دەڵێت یەک هەفتە، کۆدێک کە دەڵێت time() + 10 | The cookie lives 10 seconds ١٠ چرکە دەژی | time() + 7 * 24 * 60 * 60 |
A space, =, , or ; in the name، =، , یان ; لە ناوەکەدا | ValueError: the page stopsValueError: لاپەڕەکە دەوەستێت | Use letters, digits and _پیت، ژمارە و _ بەکاربهێنە |
$_COOKIE['x'] without checking$_COOKIE['x'] بەبێ پشکنین | Warning: Undefined array key: Undefined array key | isset() or $_COOKIE['x'] ?? 'default'isset() یان $_COOKIE['x'] ?? 'default' |
| Deleting with a different path or domainسڕینەوە بە یان دۆمەینێکی جیاواز | The cookie stays دەمێنێتەوە | Same name, path and domain; time in the pastهەمان ناو، و دۆمەین؛ کاتی ڕابردوو |
A too narrow path, e.g. '/index.php' زۆر تەسک، بۆ نموونە '/index.php' | Other pages never receive the cookieلاپەڕەکانی تر هەرگیز وەرناگرن | Use '/' or the project folder'/' یان پرۆژەکە بەکاربهێنە |
| Trusting a cookie for identity, role or priceمتمانەکردن بە بۆ ناسنامە، ڕۆڵ یان نرخ | Anyone can fake itهەر کەسێک دەتوانێت ساختەی بکات | Keep such data in a session or the databaseئەو جۆرە دراوەیە لە یان ڕابگرە |
| Printing a cookie without escapingچاپکردنی بەبێ پاراستن | XSSهێرشی XSS | htmlspecialchars($_COOKIE[...]) |
Exercises and quick checkڕاهێنان و پشکنینی خێرا
Answer the course question: What is a cookie? What are browser cookies used for, and how do you stop your browser from accepting them?
وەڵامی پرسیارەکەی کۆرسەکە بدەرەوە: چییە؟ بۆ چی بەکار دێن و چۆن ڕێگە لە دەگریت وەریانبگرێت؟
Show answerوەڵامەکە پیشان بدە
A cookie is a small piece of text (a name and a value) that a website asks the browser to store on the visitor's device. The browser sends it back to that website with every later request, so the site can recognise the visitor and remember earlier actions.
پارچە دەقێکی بچووکە (ناوێک و ) کە داوا لە دەکات لەسەر ئامێری سەردانکەر خەزنی بکات. لەگەڵ هەموو دواتردا بۆ ئەو تۆڕگەیەی دەنێرێتەوە، بۆیە دەتوانێت سەردانکەر بناسێتەوە و کارە پێشووەکانی لە بیر بێت.
Uses: keeping you logged in (through a session ID), remembering a shopping cart, saving preferences such as the language, and tracking visits for statistics and targeted advertising.
بەکارهێنانەکان: هێشتنەوەت لە ژوورەوە (لە ڕێگەی )، لە بیرگرتنی سەبەتەی کڕین، خەزنکردنی ئارەزووەکان وەک زمان و شوێنکەوتنی سەردانەکان بۆ ئامار و ڕیکلامی ئامانجدار.
To block them: open the browser's Settings (or Preferences) → Privacy and security → Cookies, and choose to block third-party cookies or all cookies, or to delete cookies when the browser closes. Browser extensions can also block cookies. Blocking all cookies stops logins from working.
بۆ ڕاگرتنیان: Settings (یان Preferences)ی بکەرەوە ← Privacy and security ← Cookies و ڕاگرتنی یان هەموو هەڵبژێرە، یان سڕینەوەی کاتێک دادەخرێت. دەتوانن ڕابگرن. ڕاگرتنی هەموو وا دەکات کار نەکات.
Write remember.php. If the visitor has no name cookie, show a form that asks for a name. When the form is sent, save the name in a cookie for 30 days and greet the visitor at once. On later visits, greet the visitor by name without the form. Then write forget.php, which deletes the cookie and goes back to remember.php.
remember.php بنووسە. ئەگەر سەردانکەر هیچ nameـی نییە، پیشان بدە کە ناو بپرسێت. کاتێک نێردرا، ناوەکە بۆ ٣٠ ڕۆژ لە خەزن بکە و دەستبەجێ بەخێرهاتنی سەردانکەر بکە. لە سەردانەکانی دواتردا، بەبێ بە ناوی خۆیەوە بەخێرهاتنی بکە. پاشان forget.php بنووسە، کە دەسڕێتەوە و دەگەڕێتەوە بۆ remember.php.
Hintئاماژە
Remember rule 1: after setcookie(), use the posted name directly. Both files are in the same folder, so the default path is the same.
یاسای ١ لە بیر بێت: دوای setcookie()، ناوە نێردراوەکە ڕاستەوخۆ بەکاربهێنە. هەردوو لە یەک فۆڵدەردان، بۆیە بنەڕەتی وەک یەکە.
Show answerوەڵامەکە پیشان بدە
<?php
$name = $_COOKIE['name'] ?? ''; // the name saved on an earlier visit, or ''
if (isset($_POST['name']) && trim($_POST['name']) !== '') {
$name = trim($_POST['name']);
setcookie('name', $name, time() + 30 * 24 * 60 * 60); // remember for 30 days
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ($name !== ''): ?>
<p>Hello, <?php echo htmlspecialchars($name); ?>! Nice to see you.</p>
<?php else: ?>
<form method="post">
Your name: <input type="text" name="name">
<button type="submit">Remember me</button>
</form>
<?php endif; ?>
</body>
</html>Hello, Shilan! Nice to see you.
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<!DOCTYPE html>
<html>
<body>
<p>Hello, Shilan! Nice to see you.</p>
</body>
</html>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The name from an earlier visit, or an empty string.
ناوەکە لە سەردانێکی پێشووەوە، یان زنجیرەنووسەیەکی بەتاڵ.
- Lineدێڕی 6
Use the new name now; the cookie arrives only with the next request.
ئێستا ناوە نوێیەکە بەکاربهێنە؛ تەنها لەگەڵ داهاتوودا دەگات.
- Lineدێڕی 7
30 days.
setcookie()runs before any HTML.٣٠ ڕۆژ.
setcookie()پێش هەموو HTMLێک کار دەکات.- Lineدێڕی 13
Always escape what came from the visitor.
هەمیشە ئەوەی لە سەردانکەرەوە هاتووە بپارێزە.
<?php
// Same name and path as in remember.php (the default path), empty value, time in the past
setcookie('name', '', time() - 3600);
header('Location: remember.php');
exit;HTTP/1.1 302 Found Set-Cookie: name=deleted; expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=0 Location: remember.php
The browser deletes the cookie and opens remember.php, which shows the form again.
دەسڕێتەوە و remember.php دەکاتەوە، کە دیسان پیشان دەدات.
This page should remember the visitor's favourite colour for one week. It has four mistakes. Find them and fix them.
ئەم لاپەڕەیە دەبێت ڕەنگی دڵخوازی سەردانکەر بۆ یەک هەفتە لە بیر بگرێت. چوار هەڵەی تێدایە. بیاندۆزەوە و ڕاستیان بکەرەوە.
<h1>My page</h1>
<?php
setcookie("favourite color", "green", "2026-12-31");
echo "Your favourite colour: " . $_COOKIE["favourite color"];Hintئاماژە
Check the order, the name, the type of expires, and how $_COOKIE is read.
ڕیزبەندی، ناو، جۆری expires و چۆنیەتی خوێندنەوەی $_COOKIE بپشکنە.
Show answerوەڵامەکە پیشان بدە
Bugs: (1) <h1> is output before setcookie(); (2) the name favourite color contains a space; (3) the expiry is a date string, not time() + seconds; (4) the page reads $_COOKIE without checking and prints it without escaping. PHP 8 stops at once with a TypeError for problem 3. Fix it, and the space in the name (problem 2) stops the page with a ValueError. Fix that too, and on a server without output buffering problem 1 gives the warning “headers already sent”, and problem 4 the warning “Undefined array key”:
هەڵەکان: (١) <h1> پێش setcookie() ؛ (٢) ناوی favourite color تێدایە؛ (٣) دەقی بەروارە، نەک time() + seconds؛ (٤) لاپەڕەکە بەبێ پشکنین $_COOKIE دەخوێنێتەوە و بەبێ پاراستن چاپی دەکات. PHP 8 دەستبەجێ بە TypeError لە کێشەی ٣دا دەوەستێت. ئەگەر ئەوە ڕاست بکەیتەوە، ناو ناوەکە (کێشەی ٢) بە ValueError لاپەڕەکە ڕادەگرێت. ئەگەر ئەویش ڕاست بکەیتەوە، لەسەر بەبێ ، کێشەی ١ «headers already sent» دەدات و کێشەی ٤ «Undefined array key»:
My page
Fatal error: Uncaught TypeError: setcookie(): Argument #3 ($expires_or_options) must be of type array|int, string given in /www/buggy.php:3
Stack trace:
#0 /www/buggy.php(3): setcookie('favourite color', 'green', '2026-12-31')
#1 {main}
thrown in /www/buggy.php on line 3<?php
// 1. setcookie() first, before any HTML
// 2. no space in the name
// 3. expires = now + 7 days, as a number of seconds
setcookie("favourite_color", "green", time() + 7 * 24 * 60 * 60);
?>
<h1>My page</h1>
<?php
// 4. check before reading, and escape when printing
$color = $_COOKIE["favourite_color"] ?? "not chosen yet";
echo "Your favourite colour: " . htmlspecialchars($color);My page Your favourite colour: not chosen yet My page Your favourite colour: green
Write lastvisit.php. On the first visit it says “This is your first visit. Welcome!”. On later visits it says “Your last visit was on (date and time)”. Keep the cookie for one year.
lastvisit.php بنووسە. لە یەکەم سەرداندا دەڵێت «This is your first visit. Welcome!». لە سەردانەکانی دواتردا دەڵێت «Your last visit was on (بەروار و کات)». بۆ یەک ساڵ ڕابگرە.
Hintئاماژە
Store time() in the cookie, and turn it into a date with date() on the next visit.
time() لە خەزن بکە و لە سەردانی داهاتوودا بە date() بیکە بە بەروار.
Show answerوەڵامەکە پیشان بدە
<?php
// Read the time of the previous visit BEFORE saving the new one
$last = isset($_COOKIE['last_visit']) ? (int) $_COOKIE['last_visit'] : 0;
// Save "now" for the next visit (one year)
setcookie('last_visit', (string) time(), time() + 365 * 24 * 60 * 60);
if ($last > 0) {
echo "Your last visit was on " . date('Y-m-d \a\t H:i', $last) . ".";
} else {
echo "This is your first visit. Welcome!";
}This is your first visit. Welcome! Your last visit was on 2026-10-16 at 11:26.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Read the old time first;
(int)protects against edited cookies.سەرەتا کاتە کۆنەکە بخوێنەوە؛
(int)دژی دەستکاریکراو دەیپارێزێت.- Lineدێڕی 6
Store a Unix timestamp as text: a cookie value must be a string.
Unix وەک دەق خەزن بکە: دەبێت بێت.
- Lineدێڕی 9
date()turns the timestamp into a readable date;\a\tprints the word “at”.date()دەکات بە بەرواری خوێندراو؛\a\tوشەی «at» چاپ دەکات.
Summary and reviewکورتە و پێداچوونەوە
- HTTP is stateless. A cookie lets a website remember small facts: the browser stores
name=valueand sends it back with every request to that site. - Create:
setcookie(name, value, expires, path, domain, secure, httponly), before any output. Only the name is required. expiresis a Unix timestamp:time() + seconds.0= until the browser closes; a past time deletes.- Read with
$_COOKIE['name'] ?? 'default'. A new cookie appears in$_COOKIEonly on the next request. - Delete with the same name, path and domain, an empty value and a past time.
- Secure = HTTPS only; HttpOnly = hidden from JavaScript; SameSite = control cross-site sending.
- Third-party cookies come from other domains embedded in a page and are used to follow visitors; you can block them in the browser settings.
- Cookies are user input: never store passwords or proof of identity in them, and escape them before printing.
- HTTP بێدۆخە. ڕێگە بە دەدات شتی بچووک لە بیر بگرێت:
name=valueخەزن دەکات و لەگەڵ هەموو بۆ ئەو تۆڕگەیە دەینێرێتەوە. - دروستکردن:
setcookie(name, value, expires, path, domain, secure, httponly)، پێش هەر . تەنها ناو پێویستە. expiresUnixـە:time() + seconds.0= تا دادەخرێت؛ کاتی ڕابردوو دەسڕێتەوە.- بە
$_COOKIE['name'] ?? 'default'بیخوێنەوە. نوێ تەنها لە داهاتوودا لە$_COOKIEدا دەردەکەوێت. - بە هەمان ناو، و دۆمەین، بەتاڵ و کاتێکی ڕابردوو بیسڕەوە.
- Secure = تەنها HTTPS؛ HttpOnly = شاراوە لە JavaScript؛ SameSite = کۆنترۆڵی ناردن لە نێوان تۆڕگەکاندا.
- لە دۆمەینەکانی ترەوە دێن کە لە لاپەڕەکەدا دانراون و بۆ شوێنکەوتنی سەردانکەران بەکار دێن؛ دەتوانیت لە ڕێکخستنەکانی ڕایانبگریت.
- وەک مامەڵە بکە: هەرگیز یان بەڵگەی ناسنامە تێیاندا خەزن مەکە و پێش چاپکردن بیانپارێزە.
Where is a cookie stored, and who sends it to the server?کووکی لە کوێ خەزن دەکرێت و کێ دەینێرێت بۆ ڕاژەکار؟
In the visitor's browser. The browser sends it automatically in the Cookie header of every request to the website (and path) it belongs to.
لە سەردانکەردا. خۆکارانە لە سەردێڕی Cookieی هەموو دەینێرێت بۆ ئەو (و ) کە هی ئەوە.
Why must setcookie() come before any output?بۆچی دەبێت setcookie() پێش هەر دەرخستەیەک بێت؟
It sends an HTTP header, and headers travel before the body. After the first output the headers are already sent, so PHP gives a warning and no cookie is set (XAMPP's output buffering can hide this).
دەنێرێت و سەردێڕەکان پێش ناوەڕۆک دەڕۆن. دوای یەکەم سەردێڕەکان پێشتر نێردراون، بۆیە PHP دەدات و هیچ دانانرێت ( XAMPP دەتوانێت ئەمە بشارێتەوە).
What is wrong with setcookie('user', 'Aram', 3600) if you want one hour?ئەگەر یەک کاتژمێرت بوێت، setcookie('user', 'Aram', 3600) چی هەڵەیە؟
3600 is a timestamp in 1970, so the cookie is already expired. Write time() + 3600.
3600 لە ١٩٧٠دا، بۆیە پێشتر بەسەرچووە. بنووسە time() + 3600.
Why did the language page still say “Bonjour” after the visitor chose Deutsch?بۆچی لاپەڕەی زمان دوای ئەوەی سەردانکەر Deutschـی هەڵبژارد هێشتا دەیوت «Bonjour»؟
Because it read $_COOKIE, which still held the old value fr sent with that request. The new cookie only arrives with the next request. Use $_POST['language'] directly, or redirect.
چونکە $_COOKIEی دەخوێندەوە، کە هێشتا نرخە کۆنەکەی frی تێدا بوو کە لەگەڵ ئەو داواکارییەدا نێردرابوو. نوێ تەنها لەگەڵ داهاتوودا دەگات. ڕاستەوخۆ $_POST['language'] بەکاربهێنە، یان ئاڕاستە بکەرەوە.
What is the difference between a first-party and a third-party cookie?جیاوازی نێوان کووکیی لایەنی یەکەم و کووکیی لایەنی سێیەم چییە؟
A first-party cookie is set by the website in the address bar. A third-party cookie is set by another domain whose content (an ad, a button) is embedded in the page.
لایەنی یەکەم ئەو تۆڕگەیە دایدەنێت کە لە شریتی ناونیشاندایە. دۆمەینێکی تر دایدەنێت کە ناوەڕۆکەکەی (ڕیکلامێک، دوگمەیەک) لە لاپەڕەکەدا دانراوە.
Why is user_id=7 in a cookie not a safe way to remember a login?بۆچی user_id=7 لە کووکییەکدا ڕێگایەکی سەلامەت نییە بۆ لە بیرگرتنی چوونەژوورەوە؟
Because the visitor controls the cookie and can change 7 to any number, becoming another user without a password. A session keeps the user id on the server.
چونکە سەردانکەر کۆنترۆڵی دەکات و دەتوانێت 7 بگۆڕێت بۆ هەر ژمارەیەک و بەبێ ببێت بە تر. ناسێنەری لەسەر هەڵدەگرێت.
Does PHP code inside an HTML comment <!-- --> run?ئایا کۆدی PHP لە ناو لێدوانێکی HTML <!-- -->دا کار دەکات؟
Yes. The server runs it; only the browser hides the result. The comment text is also output, which matters for setcookie().
بەڵێ. کارپێی دەکات؛ تەنها ئەنجامەکە دەشارێتەوە. دەقی ، کە بۆ setcookie() گرنگە.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
A short, friendly explanation of what cookies are, where they came from, how a website saves and reads them, and what third-party cookies are.
ڕوونکردنەوەیەکی کورت و هاوڕێیانە: چییە، لە کوێوە هاتووە، چۆن هەڵیدەگرێت و دەیخوێنێتەوە و چییە.
Whole video except the outro (stop at 4:37).
هەموو ڤیدیۆکە جگە لە کۆتاییەکەی (لە 4:37 ڕاوەستە).
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Sessionsسێشنەکان
Related lecturesوانە پەیوەندیدارەکان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.