w3resource

PHP script: Cookie and session variable comparison

PHP Cookies and Sessions: Exercise-16 with Solution

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.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Display last session access time.

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.