Laravel
582
w3alert.com
07-02-2020
A cookie is a small file. In which the data is stored on the client browser. Cookies are embedded with requests whenever a client requests a web browser from a web browser. Cookies are commonly used to identify the user.
Cookies are ordinarily set in an HTTP header. PHP supports HTTP cookies.
In PHP, setCookie() function is used to set/create/sent a cookie.
Syntax:
setcookie( name, value, expire, path, domain, security, httponly );
Note: Name and value parameters are the most needed parameters to create a cookie and other parameters are optional.
Parameters: There are six parameters in the setCookie() function to create a cookie.
Example: The following program is displayed below to understand the setCookie() function:
Example 1:
<?php setCookie( "My_Cookie", "John" ); // Create a cookie without optional parameters. ?>
Example 2:
<?php setCookie( "My_Cookie", "John", time()+3600*24*2 ); // Create a cookie with optional parameter for 2 day. ?>
In PHP, The global variable $_COOKIE is used to get the value of a cookie.
Before reaching the value of a cookie, it is necessary to check whether the cookie is set or not. The isset() function is used in PHP to check this situation.
Example:
The following program is shown below to check if the cookie is set or not and to get the values of the cookie:
<?php $cookie_name = "My_Cookie"; $cookie_value = "John"; setCookie( $cookie_name, $cookie_value, time()+3600*24*2 ); // Create a cookie with optional parameter for 2 day. /*check the whether condition the cookie is set or not and getting the value of a cookie.*/ if (isset( $_COOKIE[$cookie_name] ) ) { echo " The cookie is: " . $cookie_name ."<br>"; echo "The cookie value is: " . $_COOKIE[$cookie_name]; } else { echo "The cookie is not set."; } ?>
In PHP, The setCookie () function can be used to remove cookies that require the expiration date in the time parameter to be set in the past.
Example:
The following program is shown below to delete the cookie:
<?php $cookie_name = "My_Cookie"; setCookie( $cookie_name, " ", time()-60 ); // To delete a cookie. ?>
Note: If you do not set the time parameter then the cookie is automatically deleted at the end of the session.
Example:
The following example to understand PHP cookies with HTML Form.
<?php if(isset($_POST["submit"])){ setCookie( "name", $_POST["name"], time()+3600*24*2 ); } ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>Enter The Username.</p> <form method="POST"> <input type="text" name="name"> <input type="submit" name="submit"> </form> </body> </html> <?php print_r($_COOKIE); ?>