w3resource

Set a secure PHP cookie for an encrypted connection


7. Set Secure Cookie Over HTTPS

Write a PHP script to set a secure cookie that can only be transmitted over an encrypted connection.

Sample Solution:

PHP Code :

<?php
$cookieName = "my_Cookie";
$cookieValue = "Example_cookie_value";
$expirationTime = time() + 3600; // current time + 1 hour
$secureOnly = true; // Set the cookie to be transmitted only over HTTPS

setcookie($cookieName, $cookieValue, $expirationTime, "/", "", $secureOnly, true);

echo "Secure cookie named 'my_Cookie' has been set.";
?>

Sample Output:

Secure cookie named 'my_Cookie' has been set.

Explanation:

In the above exercise -

  • $cookieName: The cookie name, set to "myCookie".
  • $cookieValue: The cookie value, set to "example value".
  • $expirationTime: The cookie expiration time, calculated as the current time (time()) plus 1 hour (3600 seconds).
  • $secureOnly: A boolean variable set to true to indicate that the cookie should only be transmitted over an encrypted connection (HTTPS).

We then use the setcookie() function to set the cookie with the specified name, value, expiration time, and secure flag. In order to make the cookie accessible on the entire domain and its subdomains, the last two parameters are set to / and "".

Flowchart:

Flowchart: Set a secure PHP cookie for an encrypted connection.

For more Practice: Solve these Related Problems:

  • Write a PHP script to set a cookie named "secureUser" with the secure flag enabled and an expiration time of one hour.
  • Write a PHP function to create a secure cookie that is only transmitted over HTTPS and verify its properties.
  • Write a PHP program to set a secure cookie and check its transmission by simulating an HTTPS environment.
  • Write a PHP script to set a cookie with additional security attributes like HttpOnly and Secure, and display a confirmation message.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Destroy PHP session and unset all session variables.
Next: PHP script to check cookie existence and display a message.

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.