PHP: Cookies

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Cookies

Aims:

State management

Ways to achieve state management

There are many ways to detect that two requests come from the same client:

Cookies for state management (simplified)

Cookies example

Two types of cookie: persistent and in-memory

Two types of cookie: persistent and in-memory

Cookies in PHP: sending them

Cookies in PHP: sending them

(*unless PHP's output buffering is enabled, which it is not in our installation)

Class exercise

Assume these show the first few lines of various PHP scripts. Which of them give error messages?

  1. <?php
        output_header( 'My web page with a cookie', 'stylesheet.css' );
        setcookie( 'num_visits', $counter, time()+86400*365*5 );
    ?>


  2. <?php
        setcookie( 'num_visits', $counter, time()+86400*365*5 );
    ?>

  3.   <?php
        setcookie( 'num_visits', $counter, time()+86400*365*5 );
    ?>

Cookies in PHP: accessing them

counter.php: a simple example

Counting the number of times a page has been accessed by a client

<?php
    require_once( 'output_functions.php' );
    
    if ( ! isset($_COOKIE['num_visits']) ) 
    {
        $counter = 1;
    }
    else 
    {
        $counter = $_COOKIE['num_visits'] + 1;
    }
    setcookie( 'num_visits', $counter, time()+86400*365*5 );
    
    output_header( 'Welcome!', 'stylesheet.css' );
    output_paragraph( "You have visited this page {$counter} times" );
    output_footer( 'University College Cork' );
?>

Some of the issues with cookies