Checking cookie is set or not in PHP

A cookie is a small piece of data that the server-side application stores on the client-side (i.e., on the user’s web browser). Cookies are commonly used in web applications to store user-specific information such as login credentials, user preferences, or the contents of a shopping cart. On subsequent requests from the same client, the server can retrieve this information from the cookie.

The setcookie() function in PHP is used to set a cookie. The setcookie() function has the following basic syntax:

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

In the above general form of the «setCookie()» function, there are seven arguments, and following is a list and brief description of all seven arguments.

  • name is the name of the cookie (string)
  • value is the value of the cookie (string)
  • expire is the expiration time of the cookie (integer timestamp)
  • path is the path on the server where the cookie will be available (string, default is ‘/’)
  • domain is the domain where the cookie will be available (string, default is the current domain)
  • secure is a flag indicating whether the cookie should only be transmitted over a secure HTTPS connection (boolean, default is false)
  • httponly is a flag indicating whether the cookie should be inaccessible to client-side scripts (boolean, default is false)

Consider the following PHP code that demonstrates how to set a cookie in PHP:

setcookie("username", "william", time()+3600, "/");

The above PHP code creates a cookie called «username» with the value «william» on the server’s root path. The above «setcookie()» function takes four arguments, which are briefly described below:

  • «username» is the name of the cookie. In this case, it’s «username».
  • «william» is the value of the cookie. In this case, it’s «william».
  • time()+3600 is the expiration time of the cookie. This sets the cookie to expire in one hour (3600 seconds) from the current time. time() returns the current time as a Unix timestamp (i.e., the number of seconds since January 1, 1970). Adding 3600 to the current time gives us the timestamp for one hour from now.
  • «/» is the path on the server where the cookie will be available. In this case, it’s the root path of the server, which means the cookie will be available on all pages of the website.

Use the PHP $_COOKIE superglobal array to retrieve the cookie. As an example:

$username = $_COOKIE["username"];

Here is an example illustrating how to create cookies in PHP.

// Set the cookie name and value $cookieName = "codescracker"; $cookieValue = "Computer Programmer"; // Set the expiration time for the cookie (30 days from now) $expirationTime = time() + (86400 * 30); // 86400 seconds = 1 day // Set the cookie with the above name, value, and expiration time setcookie($cookieName, $cookieValue, $expirationTime); // Check if the cookie exists and print a message accordingly if (!isset($_COOKIE[$cookieName])) < echo "Cookie not found. A new cookie has been created."; >else < echo "Cookie exists with the name: " . $cookieName . " and value: " . $_COOKIE[$cookieName]; >?>

Here is the sample output of the above creating cookies example code in PHP. This is the screenshot of the sample output at the first run of the above PHP program in the web browser:

Читайте также:  Java get project dir

create cookie in php

Now, if you run the above creating cookie program in PHP for the first time, a cookie with the name «codescracker» and value «Computer Programmer» is created for 30 days. Therefore, if you re-run the same program or refresh your browser for the same program, you will see the following output this time:

php create cookie

If you create the above cookie for only 2 seconds, then you will see that your cookie will be created and expire in only 2 seconds. After creating your cookie for 2 seconds, if you refresh your browser after 2 seconds, you will see the message «Creating cookie..» after 2 seconds of creating your cookie using the above program in PHP.

Here is an example showing how to retrieve cookies in PHP.

// Check if the cookie exists or not if (!isset($_COOKIE[$cookieName])) < // If the cookie doesn't exist, set it with a value and expiration time $cookieValue = "Computer Programmer"; $expirationTime = time() + (86400 * 30); // 86400 seconds = 1 day setcookie($cookieName, $cookieValue, $expirationTime); > // Retrieve the cookie value and print it along with the cookie name if (isset($_COOKIE[$cookieName])) < echo "Cookie is retrieving. 
"; echo "Cookie is retrieved successfully.

"; echo "Name of the cookie = " . $cookieName . "
"; echo "Value of the cookie = " . $_COOKIE[$cookieName] . "
"; > else < echo "Error occurred.
"; echo "Exiting.
"; > ?>

Here is the sample output produced by the above retrieving cookie example code in PHP.

php retrieve cookie

In PHP, use the isset() function on the superglobal variable $_COOKIE to determine whether or not a cookie has been set. Let’s take an example of checking whether a cookie is already set or not.

    "; echo "You are ".$_COOKIE['cookieName']; > else < echo "Cookie is not set
"; echo "You can't proceed!"; > ?>

As the cookie is not set, here is the sample output produced by the above cookie example code in PHP.

php check cookie set

Now try another example to check for cookies, whether they are set or not, on the user’s computer in PHP.

    "; echo "You are ".$_COOKIE[$cookieName]; > else < echo "Cookie is not set
"; echo "You can't proceed!"; > ?>

As a result of the cookie named «codescracker» being set by the example program for creating cookies, the output of the checking whether the cookie is set or not example code in PHP will be «true» this time.

php cookie

To delete any cookie in PHP, just create the cookie again with the same name but set the expiration time to 1 hour ago or earlier, that is, set time as time()-3600.

Here is an example showing how to delete cookies in PHP from the user’s computer.

    $cookieName is deleted successfully."; ?> 

Here is an example of what the above PHP code for deleting a cookie produces.

php delete cookie

Here is an example showing how to check whether the cookie is deleted or not in PHP.

    $cookieName is not deleted."; > else < echo "The cookie $cookieName is deleted."; > ?> 

Here is an example of what the above PHP example program does when it checks to see if the cookie has been deleted.

Читайте также:  Error div style css

php cookie example

Liked this article? Share it!

Источник

It should be noted that this gets the session cookie ini file parameters, not the parameters from the cookie itself.

ie. if you set the cookie lifetime using session_set_cookie_params(12345) and then try to use session_get_cookie_params, you will not get back 12345. Instead, you will get the lifetime set in the ini file.

This function is quite handy when it comes to expiring session cookies. since Session cookies don’t automatically get destroyed (see the session_destroy page).

For instance, here’s what I plan to use to expire session cookies:

$CookieInfo = session_get_cookie_params();
if ( (empty($CookieInfo[‘domain’])) && (empty($CookieInfo[‘secure’])) ) setcookie(session_name(), », time()-3600, $CookieInfo[‘path’]);
> elseif (empty($CookieInfo[‘secure’])) setcookie(session_name(), », time()-3600, $CookieInfo[‘path’], $CookieInfo[‘domain’]);
> else setcookie(session_name(), », time()-3600, $CookieInfo[‘path’], $CookieInfo[‘domain’], $CookieInfo[‘secure’]);
>
session_destroy();

It doesn’t check to see if the path part of the session cookie is set because the defaults in php.ini have this set already, unlike domain and secure.

  • Session Functions
    • session_​abort
    • session_​cache_​expire
    • session_​cache_​limiter
    • session_​commit
    • session_​create_​id
    • session_​decode
    • session_​destroy
    • session_​encode
    • session_​gc
    • session_​get_​cookie_​params
    • session_​id
    • session_​module_​name
    • session_​name
    • session_​regenerate_​id
    • session_​register_​shutdown
    • session_​reset
    • session_​save_​path
    • session_​set_​cookie_​params
    • session_​set_​save_​handler
    • session_​start
    • session_​status
    • session_​unset
    • session_​write_​close

    Источник

    # Cookies

    An HTTP cookie is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing.

    The value of a cookie can be modified by resetting the cookie

    setcookie("user", "John", time() + 86400, "/"); // assuming there is a "user" cookie already 

    Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser.

    When modifying a cookie make sure the path and domain parameters of setcookie() matches the existing cookie or a new cookie will be created instead.

    The value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name

    A cookie is set using the setcookie() function. Since cookies are part of the HTTP header, you must set any cookies before sending any output to the browser.

    setcookie("user", "Tom", time() + 86400, "/"); // check syntax for function params 
    • Creates a cookie with name user
    • (Optional) Value of the cookie is Tom
    • (Optional) Cookie will expire in 1 day (86400 seconds)
    • (Optional) Cookie is available throughout the whole website /
    • (Optional) Cookie is only sent over HTTPS
    • (Optional) Cookie is not accessible to scripting languages such as JavaScript

    A created or modified cookie can only be accessed on subsequent requests (where path and domain matches) as the superglobal $_COOKIE is not populated with the new data immediately.

    Use the isset() function upon the superglobal $_COOKIE variable to check if a cookie is set.

    // PHP if (isset($_COOKIE['user']))  // true, cookie is set echo 'User is ' . $_COOKIE['user']; else  // false, cookie is not set echo 'User is not logged in'; > // PHP 7.0+ echo 'User is ' . $_COOKIE['user'] ?? 'User is not logged in'; 

    To remove a cookie, set the expiry timestamp to a time in the past. This triggers the browser’s removal mechanism:

    setcookie('user', '', time() - 3600, '/'); 

    When deleting a cookie make sure the path and domain parameters of setcookie() matches the cookie you’re trying to delete or a new cookie, which expires immediately, will be created.

    It is also a good idea to unset the $_COOKIE value in case the current page uses it:

    Retrieve and Output a Cookie Named user

    The value of a cookie can be retrieved using the global variable $_COOKIE . example if we have a cookie named user we can retrieve it like this

    # Syntax

    • bool setcookie( string $name [, string $value = «» [, int $expire = 0 [, string $path = «» [, string $domain = «» [, bool $secure = false [, bool $httponly = false ]]]]]] )

    # Parameters

    parameter detail
    name The name of the cookie. This is also the key you can use to retrieve the value from the $_COOKIE super global. This is the only required parameter
    value The value to store in the cookie. This data is accessible to the browser so don’t store anything sensitive here.
    expire A Unix timestamp representing when the cookie should expire. If set to zero the cookie will expire at the end of the session. If set to a number less than the current Unix timestamp the cookie will expire immediately.
    path The scope of the cookie. If set to / the cookie will be available within the entire domain. If set to /some-path/ then the cookie will only be available in that path and descendants of that path. Defaults to the current path of the file that the cookie is being set in.
    domain The domain or subdomain the cookie is available on. If set to the bare domain stackoverflow.com then the cookie will be available to that domain and all subdomains. If set to a subdomain meta.stackoverflow.com then the cookie will be available only on that subdomain, and all sub-subdomains.
    secure When set to TRUE the cookie will only be set if a secure HTTPS connection exists between the client and the server.
    httponly Specifies that the cookie should only be made available through the HTTP/S protocol and should not be available to client side scripting languages like JavaScript. Only available in PHP 5.2 or later.

    # Remarks

    It is worth noting that mere invoking setcookie function doesn’t just put given data into $_COOKIE superglobal array.

    For example there is no point in doing:

    setcookie("user", "Tom", time() + 86400, "/"); var_dump(isset($_COOKIE['user'])); // yields false or the previously set value 

    The value is not there yet, not until next page load. The function setcookie just says «with next http connection tell the client (browser) to set this cookie«. Then when the headers are sent to the browser, they contain this cookie header. The browser then checks if the cookie hasn’t expired yet, and if not, then in http request it sends the cookie to the server and that’s when PHP receives it and puts the contents into $_COOKIE array.

    Источник

Оцените статью