w3resource

PHP script: Cookie and session variable comparison


16. Set Cookie and Session Variable with Same Name

Write a PHP script to set a cookie and a session variable with the same name. Display their values to compare.

Sample Solution:

PHP Code :

<?php
// Set the session save path
session_save_path('i:/custom/');
$cookieName = "myCookie";
$value = "Cookie Value";

// Set the cookie
setcookie($cookieName, $value, time() + 3600, "/");

// Start the session
session_start();

// Set the session variable
$_SESSION[$cookieName] = $value;

// Display the cookie value
echo "Cookie value: " . $_COOKIE[$cookieName] . "
"; // Display the session variable value echo "Session variable value: " . $_SESSION[$cookieName]; ?>

Sample Output:

Cookie value: Cookie Value
Session variable value: Cookie Value

Explanation:

In the above exercise -

  • We define the cookie name as $cookieName and the value as $value ("Example Value").
  • Use setcookie() to set the cookie with the specified name, value, expiration time (1 hour in this example), and path ("/" to make it accessible on the entire domain).
  • Start the session using session_start() to initialize the session.
  • Set the session variable with the same name as the cookie using $_SESSION[$cookieName] = $value.
  • Display the cookie value using $_COOKIE[$cookieName].
  • Display the session variable value using $_SESSION[$cookieName].

Flowchart:

Flowchart: PHP script: Cookie and session variable comparison.

For more Practice: Solve these Related Problems:

  • Write a PHP script to set both a cookie and a session variable with the same name, then display their values to highlight differences.
  • Write a PHP function to assign a value to a cookie and a session variable with an identical key and compare how they are accessed in different scopes.
  • Write a PHP program to test retrieval of a cookie and session variable sharing the same name and document the order of precedence.
  • Write a PHP script to set a cookie and a session variable with the same identifier and output their values for debugging purposes.

Go to:


PREV : Display Last Session Access Time.
NEXT : PHP OOP Exercises Home.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.