Skip to main content
April 1, 2026Noble Desktop Publishing Team/11 min read

Cookies: Free PHP & MySQL Tutorial

Master PHP Cookie Implementation and User Tracking

Core PHP Cookie Concepts

Cookie Creation

Using setcookie() function with proper parameters for name, value, and expiration time. Cookies enable persistent user data storage across sessions.

User Tracking

Implementing visitor counters and session management to gather analytics data. Track landing pages, visit frequency, and referral sources.

Data Integration

Combining cookie data with form submissions and email notifications. Provides comprehensive user insights for business intelligence.

Topics Covered in This PHP & MySQL Tutorial:

Master advanced visitor tracking by implementing cookies, monitoring visit frequency, and automatically emailing comprehensive visitor analytics data

Tutorial Prerequisites

0/4

Exercise Preview

cookies track visitors example

Exercise Overview

While basic analytics platforms like Google Analytics provide valuable insights into visitor behavior, sophisticated web applications require deeper integration between user tracking and business processes. This tutorial demonstrates how to implement server-side visitor tracking using PHP cookies, enabling you to capture granular user journey data and seamlessly integrate it with form submissions and email notifications.

By storing visitor information such as entry points, referral sources, visit frequency, and session timestamps in cookies, you create a comprehensive user profile that travels with each visitor throughout their journey on your site. When users eventually convert through form submissions, this rich contextual data is automatically included, providing invaluable insights for lead qualification, marketing attribution, and customer journey optimization.

Cookie-Based Analytics Advantage

While anonymous analytics provide basic visitor data, cookie-based tracking with form integration offers deeper customer insights including landing pages, visit frequency, and referral sources.

Initial Setup Before Moving on

If you are doing this exercise in a classroom environment or repeating the tutorial, you must complete the following steps to ensure a clean testing environment. First-time users working independently can skip this section.

  1. In your browser, navigate to the setup script:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/setUp.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/setUp.php
  2. This script will clear all existing cookies, providing a fresh baseline for testing our visitor tracking implementation.

  3. Close the page once the script completes. You're ready to begin!

Environment Setup Process

1

Clear Previous Cookies

Navigate to setUp.php to reset cookie data for fresh exercise start

2

Verify Server Configuration

Ensure localhost server is running on correct port (8888 for Mac, 80 for Windows)

3

Access Project Files

Confirm phpclass/Tracking-Visitors-With-Cookies folder structure is accessible

Coding the Page

We'll begin by implementing the core cookie functionality, starting with a visit counter and expanding to capture comprehensive visitor analytics. Understanding PHP's setcookie() function is essential for this implementation.

  1. In your code editor, open form.php from the Tracking-Visitors-With-Cookies folder in the phpclass folder.

    Our first objective is implementing a robust visit tracking system using cookies. We'll establish a visit counter initialized at 1 for new visitors, with extended expiration times to maintain tracking consistency across extended user journeys.

    PHP's setcookie() function provides comprehensive cookie management with the following parameter structure:

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

    For our implementation, we'll focus on the essential parameters: name, value, and expiration. Note that expiration values must be Unix timestamps in seconds, easily generated using PHP's time() function.

  2. Let's implement our first tracking cookie. At the very top of the page, above the doctype declaration, add the following code:

    <?php 
        $expiration = 60*60*24*365*3;
        setcookie("visits",1, time()+$expiration);
    ?>
    <!DOCTYPE HTML>

    We're establishing a three-year expiration period by calculating seconds mathematically rather than using raw numbers. This approach improves code maintainability and makes duration adjustments more intuitive. The cookie expiration always uses the pattern time() + duration_in_seconds to set a future timestamp.

  3. Next, we'll implement timestamp tracking using PHP's powerful date() function. Our target format will be human-readable timestamps like:

    October 21, 2026, 5:15 pm

    Let's experiment with date formatting by adding this test code:

    <?php 
        $expiration = 60*60*24*365*3;
        setcookie("visits",1, time()+$expiration);
        echo date("M j, Y");
        exit();
    ?>

    The format string uses: M for abbreviated month names (Oct), j for day without leading zeros (1 or 22), and Y for four-digit years (2026). The exit() function halts script execution, allowing us to focus on this output without rendering the full page.

  4. Save the file and test in your browser:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php

    You should see a date display similar to: Dec 15, 2026

  5. Return to your code editor to refine the timestamp format.

  6. Now let's enhance our date format to include precise timing information. Modify the echo statement:

    setcookie("visits",1, time()+$expiration);
    echo date("F j, Y, g:i a");
    exit();

    For comprehensive date formatting options and parameters, consult the official PHP documentation at php.net/manual/en/function.date.php. This resource provides extensive formatting possibilities for various international and application-specific requirements.

  7. Test the updated format in your browser:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php

    The output should now display: December 15, 2026, 5:35 pm

  8. With our date formatting perfected, let's implement the actual cookie storage mechanism.

  9. Replace the testing code with our production cookie implementation:

    setcookie("visits",1, time()+$expiration);
    setcookie("entryDateTime", date("F j, Y, g:i a"), time()+$expiration);
  10. Save the file.

  11. Now we'll create our cookie verification system. Open thankyou.php from the Tracking-Visitors-With-Cookies folder.

    This pre-built action page will serve as our cookie validation endpoint, allowing us to verify that our tracking data is being captured correctly.

  12. Locate the comment Display cookies here around line 17.

  13. Replace that comment with our cookie display logic:

    <?php 
       echo $_COOKIE['visits'];
       echo '<br>';
       echo $_COOKIE['entryDateTime'];
    ?>

    Cookie values are accessed using the superglobal $_COOKIE['cookieName'] syntax, which follows the same pattern as $_POST for form processing. This consistent approach makes cookie manipulation intuitive for developers familiar with PHP's superglobal arrays.

  14. Test the cookie functionality:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  15. Click Signup Now! without filling out the form. If the implementation is working correctly, you'll see your cookie values displayed on the thank you page.

    Next, we'll implement URL tracking to capture entry points and referral sources. Rather than developing this functionality from scratch, we'll leverage a proven solution that handles the complexities of URL parsing, HTTPS detection, and port management.

  16. Open entryURL.php from the Tracking-Visitors-With-Cookies folder to access our URL parsing function.

  17. Select and copy all the code from this file.

  18. Close the entryURL.php file.

  19. Return to form.php.

  20. Insert the copied code between the $expiration variable and the first setcookie() function:

    $expiration = 60*60*24*365*3;
    
    function currentPageURL() {
       $isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
       $port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
       $port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
       $url = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
       return $url;
    }
    
    $entryURL = currentPageURL();
    
    setcookie("visits",1, time()+$expiration);
    setcookie("entryDateTime", date("F j, Y, g:i a"), time()+$expiration);

    This robust function utilizes PHP's $_SERVER superglobal to construct complete URLs, automatically handling secure connections (HTTPS), custom ports (like :8888 in development), and query parameters. The function returns a fully qualified URL that we store in $entryURL.

  21. Implementing referrer tracking is more straightforward, though we must account for cases where referrer information isn't available. Add this code below your URL function:

    $cameFromURL = 'none';
    if ( isset($_SERVER['HTTP_REFERER']) ) {
       $cameFromURL = $_SERVER['HTTP_REFERER'];
    }

    We establish a default value of 'none' for $cameFromURL because referrer data isn't always available due to privacy settings, direct navigation, or security policies. This defensive programming approach prevents errors while maintaining data consistency.

  22. Now we can implement cookies for both entry page and referrer tracking. Add these cookie declarations:

    setcookie("visits",1, time()+$expiration);
    setcookie("entryDateTime", date("F j, Y, g:i a"), time()+$expiration);
    setcookie("entryPage", $entryURL, time()+$expiration);
    setcookie("cameFrom", $cameFromURL, time()+$expiration);
  23. Save the file and switch to thankyou.php to update our display logic.

  24. Enhance the cookie display section to include our new tracking data:

    echo $_COOKIE['visits'];
    echo '<br>';
    echo $_COOKIE['entryDateTime'];
    echo '<br>';
    echo $_COOKIE['entryPage'];
    echo '<br>';
    echo $_COOKIE['cameFrom'];
  25. Test the enhanced tracking system:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  26. Click Signup Now! to verify that all cookie values are being captured and displayed correctly on the thank you page.

Cookie Expiration Best Practice

Set cookie expiration to 3 years (60*60*24*365*3 seconds) to account for long periods between first visit and form submission.

Essential Cookie Parameters

Name Parameter

Unique identifier for the cookie. Use descriptive names like 'visits' or 'entryDateTime' for clarity.

Value Parameter

Data to store in the cookie. Can be numbers, strings, or formatted dates depending on tracking needs.

Expiration Parameter

Unix timestamp determining cookie lifespan. Use time() + seconds for future expiration dates.

Tracking the Number of Visits

Our current implementation creates new cookies on every page load, which doesn't provide accurate visit tracking. We need to implement intelligent logic that increments the visit counter appropriately while preserving initial visit data. This section will transform our basic cookie system into a sophisticated visitor analytics platform.

  1. Return to your code editor and open form.php.

  2. We'll implement conditional cookie setting to ensure entry page and referrer data are captured only on first visits. Wrap your existing code in a conditional statement that checks for first-time visitors:

    $expiration = 60*60*24*365*3;
    
    if (!isset($_COOKIE["visits"]) ) {
       function currentPageURL() {
       $isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");

    Code Omitted To Save Space

    setcookie("entryPage", $entryURL, time()+$expiration);
       setcookie("cameFrom", $cameFromURL, time()+$expiration);
    }

    This conditional logic ensures that entry page, referrer, and initial timestamp data are captured only during the first visit. Subsequent visits will preserve this original context while updating visit counts.

  3. Save the file.

  4. Now we'll implement visit counter logic for returning visitors. Add an else clause that increments the visit count:

    setcookie("visits",1, time()+$expiration);
       setcookie("entryDateTime", date("F j, Y, g:i a"), time()+$expiration);
       setcookie("entryPage", $entryURL, time()+$expiration);
       setcookie("cameFrom", $cameFromURL, time()+$expiration);
    }
    else {
       $v = $_COOKIE["visits"];
       $v++;
       setcookie("visits", $v, time()+$expiration);
    }

    The $v++ operator provides a concise way to increment variables by one. We retrieve the current visit count, increment it, and update the cookie with the new value, maintaining visit history across sessions.

  5. Test the visit tracking functionality:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  6. Test the incrementing behavior by following these steps:

    • Click Signup Now
    • Use the browser's back button
    • Reload the page
    • Click Signup Now again
    • Repeat this process several times
    • Notice how the Number of Times Visited increases with each page reload
  7. While our visit counter works, it's currently incrementing on every page load rather than once per session. For accurate analytics, visits should represent distinct sessions, not individual page loads. We'll implement session-based tracking using a temporary cookie.

  8. Add a session tracking cookie that expires when the browser closes:

    setcookie("visits",1, time()+$expiration);
       setcookie("entryDateTime", date("F j, Y, g:i a"), time()+$expiration);
       setcookie("entryPage", $entryURL, time()+$expiration);
       setcookie("cameFrom", $cameFromURL, time()+$expiration);
    }
    else {
       $v = $_COOKIE["visits"];
       $v++;
       setcookie("visits", $v, time()+$expiration);
    }
    setcookie("currentlyHere", "true");
  9. Now we'll modify our visit increment logic to respect session boundaries. Change the else to an elseif statement:

    setcookie("visits",1, time()+$expiration);
       setcookie("entryDateTime", date("F j, Y, g:i a"), time()+$expiration);
       setcookie("entryPage", $entryURL, time()+$expiration);
       setcookie("cameFrom", $cameFromURL, time()+$expiration);
    }
    elseif (!isset($_COOKIE["currentlyHere"]) ) {
       $v = $_COOKIE["visits"];
       $v++;
       setcookie("visits", $v, time()+$expiration);
    }
    setcookie("currentlyHere", "true");

    This logic increments the visit counter only when the currentlyHere cookie doesn't exist, which occurs at the beginning of each new session. Once set, this session cookie prevents additional increments until the browser is closed and a new session begins.

  10. Test the session-based visit tracking:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  11. Verify that the visit counter now behaves correctly:

    • Click Signup Now, then navigate back and Reload multiple times
    • Click Signup Now again and observe that the Number of Times Visited remains constant during the session

Visit Tracking Approaches

FeaturePage Load TrackingSession-Based Tracking
AccuracyInflated countsTrue visit counts
ImplementationSimple incrementSession cookie logic
Business ValueMisleading metricsActionable analytics
Recommended: Use session-based tracking with currentlyHere cookie for accurate visit counting
Cookie Validation Required

Always check if cookies are set using isset() before accessing values to prevent errors when users have cookies disabled.

Sending an Email with the Cookie Info

The final step in our visitor tracking implementation involves integrating our analytics data with form processing and email notifications. This creates a comprehensive lead intelligence system that automatically includes visitor context with every form submission, providing valuable insights for sales and marketing teams.

  1. Return to your code editor and update the form action to point to our processing script.

  2. Around line 45, modify the form action attribute:

    <form action="form-action.php" method="post" name="signup" id="signup">

    This connects our form to form-action.php, which handles validation before passing data to form-send-email.php for email processing. This multi-stage approach ensures data integrity and proper error handling.

  3. Save the form file.

  4. Open form-send-email.php to configure our email integration. This pre-built script requires environment-specific configuration before we can add our cookie data.

  5. Configure the email recipient on line 2 based on your development environment:

    • Mac users (using a real email service):
    $to = "youremail@gmail.com";
    • Windows users (using local testing):
    $to = "newuser@localhost";

    With email configuration complete, we'll implement cookie integration. Since users might have cookies disabled, we must implement robust error handling to prevent email failures. Rather than writing repetitive validation code, we'll use an elegant array-based approach to process multiple cookies efficiently.

  6. Locate the comment //add cookies here around line 15.

  7. Add our cookie processing array below that comment:

    $cookies = array('visits', 'entryDateTime', 'entryPage', 'cameFrom');

    This array contains all the cookie names we want to include in our email notifications. Using an array-based approach makes our code more maintainable and allows easy addition or removal of tracked data points.

  8. Implement a foreach loop to process each cookie systematically:

    $cookies = array('visits', 'entryDateTime', 'entryPage', 'cameFrom');
    foreach ( $cookies as $value ) {
    
    }

    This loop will iterate through our cookie array, with $value representing each cookie name in turn, allowing us to process them with consistent logic.

  9. Add cookie validation within the loop to ensure data integrity:

    $cookies = array('visits', 'entryDateTime', 'entryPage', 'cameFrom');
    foreach ( $cookies as $value ) {
       if ( isset($_COOKIE[$value]) ) {
    
       }
    }
  10. Complete the implementation by appending validated cookie data to the email message:

    $cookies = array('visits', 'entryDateTime', 'entryPage', 'cameFrom');
    foreach ( $cookies as $value ) {
       if ( isset($_COOKIE[$value]) ) {
          $message .= $value . ": " . $_COOKIE[$value] . "\n";
       }
    }

    This final step creates properly formatted email content by concatenating each cookie name with its corresponding value, separated by newlines for readability. The result is a comprehensive visitor profile automatically included with every form submission, providing valuable context for lead qualification and customer journey analysis.

Email Integration Workflow

1

Update Form Action

Change form action from thankyou.php to form-action.php for processing

2

Configure Email Settings

Set recipient email address in $to variable based on your environment

3

Loop Through Cookie Array

Use foreach loop to check and append each cookie value to email message

4

Test Complete Workflow

Submit form and verify email receipt with all cookie data included

Efficient Cookie Processing

Using an array of cookie names with foreach loop eliminates code repetition and makes adding new tracking cookies simple.

Key Takeaways

1PHP setcookie() function requires name, value, and expiration parameters with expiration as Unix timestamp
2Cookie expiration should account for long periods between visits, typically set to 3 years for user tracking
3Session-based visit counting using currentlyHere cookie provides more accurate analytics than page-load counting
4Always validate cookie existence with isset() before accessing values to handle disabled cookies gracefully
5Date formatting with PHP date() function enables human-readable timestamps in cookie data
6Combining cookie data with form submissions provides comprehensive user journey insights
7Using arrays and foreach loops for cookie processing reduces code repetition and improves maintainability
8Proper form action configuration links user tracking data with email notification systems effectively

RELATED ARTICLES