3. Decisions, Functions, String, Array & Exception Handling
3. Decisions, Functions, String, Array & Exception Handling
5. Cookies in PHP
What are Cookies?
Cookies are small pieces of data stored on the client's browser,
created on the server-side. They are sent with each request to
the server, allowing the server to recognize the user.
Usage: Set with setcookie(), accessed via $_COOKIE.
Example:
Set a Cookie
setcookie("user", "Sonoo", time() + 3600); // Expires in 1 hour
Access a Cookie
echo $_COOKIE["user"]; // Output: Sonoo if cookie is set
Delete a Cookie
setcookie("user", "", time() - 3600); // Expires in the past to
delete
PHP $_COOKIE Superglobal:
Use the $_COOKIE superglobal to retrieve cookie values:
$value = $_COOKIE["CookieName"];
Example of PHP Cookie (cookie1.php):
Set Cookie and Check if it Exists:
<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
o First Request Output: "Sorry, cookie is not found!"
o After Refresh: "Cookie Value: Sonoo"
Sessions in PHP
Definition: Used to store data across multiple pages for a single
user session.
Usage: Started with session_start(), accessed via $_SESSION.
Example:
Start a Session and Set Data
<?php
session_start();
$_SESSION["user"] = "Sachin";
echo "Session information is set.";
?>
Retrieve Session Data
<?php
session_start();
echo "User is: " . $_SESSION["user"];
?>
Session Counter
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo "Page Views: " . $_SESSION['counter'];
?>
Destroy a Session
<?php
session_start();
session_destroy();
?>
PHP Arrays
Arrays in PHP allow you to store multiple values in a single variable.
Indexed Array
An array with numeric keys.
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
2. Associative Array
An array with named keys.
$ages = array("Peter" => 35, "Ben" => 37);
echo $ages["Peter"]; // Outputs: 35
3. Multidimensional Array
An array containing other arrays.
$students = array(
array("John", 18),
array("Jane", 19),
array("Jack", 20)
);
echo $students[1][0]; // Outputs: Jane
try {
$number = -1;
if ($number < 0) {
throw new CustomException("Number must be positive");
}
} catch (CustomException $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
Output:
Caught exception: Number must be positive
Explanation:
In the above example, the throw statement creates a
CustomException when $number is less than 0.
The catch block handles the exception by printing the error
message using $e->getMessage().