18.
Write a program in PHP for setting and retrieving a cookie
<?php
// Set a cookie with a name, value, expiration time (in seconds)
$cookie_name = "user";
$cookie_value = "John Doe";
$expiration = time() + (86400 * 30); // Cookie will expire in 30 days (86400 seconds = 1 day)
setcookie($cookie_name, $cookie_value, $expiration, "/"); // "/" makes the cookie available across
the entire domain
echo "Cookie '" . $cookie_name . "' is set!";
?>
<?php
// Check if the cookie is set and retrieve its value
if (isset($_COOKIE["user"])) {
echo "Cookie 'user' value is: " . $_COOKIE["user"];
} else {
echo "Cookie named 'user' is not set.";
?>
20. Write a program in PHP for exception handling for i) divide by zero ii)
checking date format.
i) Divide by zero
<?php
function divideNumbers($numerator, $denominator) {
try {
if ($denominator === 0) {
throw new Exception("Division by zero error.");
$result = $numerator / $denominator;
return $result;
} catch (Exception $e) {
return $e->getMessage();
// Example usage:
$numerator = 10;
$denominator = 0;
$result = divideNumbers($numerator, $denominator);
echo "Result: " . $result; // Output will be the error message
?>
ii) Checking date format
<?php
function validateDateFormat($dateString) {
try {
$date = date_create_from_format('Y-m-d', $dateString);
if (!$date) {
throw new Exception("Invalid date format. Date should be in YYYY-MM-DD format.");
return $date->format('Y-m-d'); // Return the formatted date
} catch (Exception $e) {
return $e->getMessage();
}
// Example usage:
$dateString = '2023-13-40'; // Invalid date format
$validatedDate = validateDateFormat($dateString);
echo "Validated Date: " . $validatedDate; // Output will be the error message
?>
17.Write a program in PHP to Validate Input
<?php
$name = $email = "";
$nameErr = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
// Validate email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// Check if email address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
// Function to sanitize input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error"><?php echo $nameErr;?></span>
<br><br>
Email: <input type="text" name="email">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Output: