Today, I learned about the "Cookies."
A web application consists of a series of disconnected HTTP requests to a web server.
In HTTP, we can pass information using:
- Query Strings (URL, header)
- Hidden Form Fields
Use Query Strings to Save State Information
- Seperate individual name = value pairs within the query string using
- Ap question mark (?) and a query string are automatically appended to the URL of a server-side script for any formas that are submitted with the GET method.
- Add a question mark immediately after a URL to pass information from one Web page to another.
ex)
<a href="http://www.URL.com/TargetPage.php?firstName=Don&lastName=Gosselin&occupation=writer:>Link Text</a>
Use Hidden From Fields
Create hidden form fields with the <input> element
- Temporarily store data that needs to be sent to server that a user does not need to see
<form action="CourseListings.php" method="get">
<p><input type="submit" value="Register for Classes" />
<input type="hidden" name="diverID" value="<? $DiverID ?>"/></p>
</form>
Now, we are gonna learn about the Cookies at the User.
Cookies
Cookies are a client-side approach for persisting state information.
They are name=value pairs that are saved within one or more text files that are managed by the browser.
One typical use of cookies in a website is to "remember" the visitor so that the server can customize the site for the user.
Cookies cannot be shared outside of a domain.
This is how cookies work.
Using Cookies in PHP
Cookies in PHP are created using the setcookie() function and are retrieved using the $_COOKIES superglobal associative array.
Cookies created without expirytime are temporary only for the current browser session.
Cookies must be written before any other page output.
// Writing a cookie
$expiryTime = time()+60*60*24;
//create a cookie
$name = "username";
$value = "Ricardo";
setcookie($name, $value, $expiryTime);
// Reading a cookie
if (!isset($_COOKIE['username'])){echo "this cookie doesn't exist";}
else {
echo "The username retrieved from the cookie is: ".$_COOKIE['username'];
}
// loop through all cookies in request
foreach ($_COOKIE as $name => $value){
echo "Cookie: $name = $value";
}
Deleting Cookies
- To delete a persistent cookie before the time assigned to the expires argument elapse, assign a new expiration value that is sometime in the past
- Do this by subtracting any number of seconds from the time() function
setcookie("username","",time()-3600);
Law on cookies
Websites must:
- Tell people the cookies are there an what cookies are being used
- Explain what the cookies are doing and why, and
- Get the user;s consent to store a cookies on their device
'Web Programming ๐ > Back-End ๐ฅท๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
URL Redirection in PHP (0) | 2023.05.07 |
---|---|
Session with PHP (0) | 2023.05.07 |
PHP Exercise: GuessGame (0) | 2023.04.25 |
PHP Exercise: popcorn bill (0) | 2023.04.25 |
PHP Form (0) | 2023.04.25 |