PHP Cookies: A tutorial to Create, Modify, and Delete with Example

A cookie (browser cookies) is a little data file that a web server requests from a user’s browser to save.

This data is then present in every request back to the server. Its function also means that the data is in pairs of keys and values.

Furthermore, the cookie’s name is automatically given to a variable with an identical name.

Create Cookies With PHP

To set cookies in PHP projects, we use the setcookie() method that specifies a cookie to be transmitted alongside the other HTTP headers.

Similar to other headers, cookies must be delivered before any script output (this is a protocol restriction). In return, this strategy permits a website to distinguish between new and returning visitors.

Syntax:

We use the proper declaration of the setcookie() method through the syntax below.

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

Remember that in the setcookie() method, the name is the only required parameter and others were optional.

The example below shows how to create or retrieve the PHP cookies in a program.

Example:

<!DOCTYPE html>
<?php
$cookie_name = "Cookie";
$cookie_value = "ITSourceCode.com";
setcookie($cookie_name, $cookie_value, "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
     echo "The '" . $cookie_name . "' is set!<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p>Try to reload to see the value of the cookie.</p>

</body>
</html>

Output:

The 'Cookie' is set!
Value is: ITSourceCode.com

Try to reload to see the value of the cookie.

Program Output explanation:

In this example, you will see that the parameters included in the setcookie() function were only the name and value.

But you can include other parameters to the function if you want to specify the time and scope of the PHP cookie for the website.

Now, to explain the program, we have the cookie name “Cookie” and its value is “ITSourceCode“. Next, we use the if-else statement with isset() function to test if the cookie is set or not.

It also adds a statement that says “Try to reload to see the value of the cookie.“.

Now, here’s an example program to modify a cookie in PHP.

Example:

<!DOCTYPE html>
<?php
$cookie_name = "new";
$cookie_value = "ITSC";
setcookie($cookie_name, $cookie_value, "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
     echo "The '" . $cookie_name . "' cookie is set!<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p>Try to reload to see the value of the cookie.</p>

</body>
</html>

Output:

The 'new' cookie is set!
Value is: ITSC

Try to reload to see the value of the cookie.

Program Output explanation:

The possible action that you may take to modify a cookie is to rewrite its attributes like name, value, and others within the setcookie() function.

Therefore the function is still the same, you just have to change the parameters of a cookie to implement the modification.

Now, how do we delete a cookie? Here’s an example,

Example:

<!DOCTYPE html>
<?php
$cookie_name = "new";
$cookie_value = "ITSC";
setcookie($cookie_name, $cookie_value, time() - 1000);
?>
<html>
<body>

<?php
echo "The '" .$cookie_name. "' cookie is deleted.";
?>

</body>
</html>

Output:

The 'new' cookie is deleted.

Program Output explanation:

To delete a cookie in your PHP project, simply set the time() in the past to indicate that the cookie application is already done.

The program will automatically delete the cookie once its time has expired.

Check if Cookies are Enabled

This time, let us know how to check if PHP cookies are enabled.

Example:

<?php
$cookie_name = "new";
$cookie_value = "ITSC";
setcookie($cookie_name, $cookie_value);
?>
<html>
<body>

<?php
if(count($_COOKIE) != 0) {
  echo "Cookies are enabled.";
} else {
  echo "Cookies are disabled.";
}
?>

</body>
</html>

Output:

Cookies are enabled.

Program Output Explanation:

The program’s output confirms that “Cookies are enabled.” in the program since it has the cookie that is set for the web.

But if the time has expired, the cookie is automatically disabled.

Frequently Ask Questions (FAQs)

To set cookies in PHP projects, we use the setcookie() method.

What is a $_ cookie?

The cookie’s name is automatically given to a variable with an identical name such as “user” which will convert into “$user” with the cookie value. $_cookie or $_COOKIE is the automatic name of the cookie if there’s no prior name.

In PHP, a cookie is a file from a server placed on the user’s computer used to identify the website’s visitors.

So, whenever the same computer requests a page using a browser, it will also send the cookie. You can therefore both generate and retrieve cookie values through PHP.

Where does PHP store cookies?

Once the user accepts cookies, they are automatically stored on the client’s computer. Nonetheless, the path simply restricts which distant pages can access the cookies.

How many types of cookies are there in PHP?

There are two types of cookies in PHP; session cookies and persistent cookies.

What is the difference between sessions and cookies in PHP?

The primary difference between a session and a cookie is that session data is stored on the server while cookie data is stored in the visitor’s web browser.

Since sessions are saved on the server, they are more secure than cookies.

Conclusion

In conclusion, the PHP cookies are now clear that they are used by websites to maintain and observe their clients as well as provide necessary information for the patron clients.

Additionally, site owners can gain interactions and feedback from their users through cookies. It can help them monitor users’ activities and improve their site in particular areas.

If you want further discussions, tap us through the comments.

Common use cases for PHP Cookies: A tutorial to Create, Modify, and Delete

  • Web application development. Full-stack PHP apps using vanilla PHP or Laravel/Symfony frameworks.
  • WordPress plugin/theme development. Custom functionality for the world’s most popular CMS.
  • API development. REST or GraphQL endpoints serving mobile apps and SPAs.
  • CLI tools. Command-line scripts for cron jobs, data migration, or automation.
  • Legacy code maintenance. PHP powers a large share of the web; understanding it is a durable skill.

Working code example

<?php
declare(strict_types=1);

class UserService {
    public function getGreeting(string $name): string {
        if ($name === "") {
            throw new InvalidArgumentException("Name is required");
        }
        return "Welcome, " . htmlspecialchars($name);
    }
}

$service = new UserService();
echo $service->getGreeting("Alice");
?>

Best practices

  • Enable strict types. declare(strict_types=1) at the top of every file catches type coercion bugs.
  • Use Composer. Modern PHP uses Composer for dependency management, autoloading, and PSR-4 class naming.
  • Follow PSR standards. PSR-12 for coding style, PSR-4 for autoloading, PSR-3 for logging.
  • Write unit tests with PHPUnit. Aim for 70%+ code coverage on business-critical modules.
  • Use static analysis. PHPStan or Psalm catch many bugs before code runs.

Common pitfalls

  • Global state. Overusing global variables makes testing hard. Prefer dependency injection.
  • SQL concatenation. Always use prepared statements. Never concatenate user input into SQL strings.
  • Missing type declarations. Old PHP allowed loose types. Modern PHP encourages strict typing everywhere.
  • Ignoring errors. Set error_reporting(E_ALL) in development. Handle errors explicitly in production.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Mary Grace G. Patulada


Programmer & Technical Writer at PIES IT Solution

Mary Grace G. Patulada (pen name ‘Nym’) is a programmer and writer at PIES IT Solution with a BSIT background from Carlos Hilado Memorial State College, Binalbagan Campus. Authored 370+ UML diagram tutorials and capstone documentation guides at itsourcecode.com. Specializes in UML (class, use case, activity, sequence, component, deployment), DFD, and ER diagrams for BSIT capstone projects.

Expertise: UML Diagrams · DFD · ER Diagrams · Use Case Diagrams · Activity Diagrams · Capstone Documentation · PHP
 · View all posts by Mary Grace G. Patulada →

Leave a Comment