How does the process of setting and updating cookies in PHP differ from handling sessions for transporting data between pages?
Setting and updating cookies in PHP involves using the setcookie() function to create a cookie with a specified name, value, and optional parameters like expiration time. Cookies are stored on the client-side and can be accessed and modified by both the client and server. On the other hand, handling sessions in PHP involves using the session_start() function to start or resume a session, and then storing and accessing data in the $_SESSION superglobal array. Sessions are stored on the server-side and are typically more secure than cookies for transporting sensitive data between pages.
// Setting a cookie
setcookie("user", "John Doe", time() + 3600, "/");
// Updating a cookie
if(isset($_COOKIE['user'])){
$user = $_COOKIE['user'];
$user = "Jane Smith";
setcookie("user", $user, time() + 3600, "/");
}
// Starting a session
session_start();
// Storing data in session
$_SESSION['user'] = "John Doe";
// Accessing data from session
$user = $_SESSION['user'];
// Destroying a session
session_destroy();
Keywords
Related Questions
- What is the role of JavaScript in making table rows clickable for opening in a new window?
- In what ways can the reservation of class names in PHP impact the development and execution of scripts?
- What are the advantages of using stream functions like fread over file_get_contents for reading large files in PHP?