0% found this document useful (0 votes)
37 views13 pages

9th To 15th PHP Prgrms

The document provides a series of PHP programs for various applications, including a student registration form, complaint registration form, exception handling, email sending and receiving, cookie-based visit tracking, an online shopping cart, and a demonstration of introspection and serialization. Each program includes a description, code snippets, and expected outputs. The examples illustrate fundamental PHP concepts such as form handling, session management, error handling, and object serialization.

Uploaded by

logesh ramesh92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views13 pages

9th To 15th PHP Prgrms

The document provides a series of PHP programs for various applications, including a student registration form, complaint registration form, exception handling, email sending and receiving, cookie-based visit tracking, an online shopping cart, and a demonstration of introspection and serialization. Each program includes a description, code snippets, and expected outputs. The examples illustrate fundamental PHP concepts such as form handling, session management, error handling, and object serialization.

Uploaded by

logesh ramesh92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

9.Constrct a php program for a student registration form.

Description:

1.register.php: Displays a simple form with fields for name, email, and course. Once the user fills it out
and submits, the data is sent to submit.php.

2.submit.php: Receives the form data and prints it out on the webpage.

Program:

1.Create a file named register.php for the registration form.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Student Registration</title>

</head>

<body>

<h2>Student Registration Form</h2>

<form method="POST" action="submit.php">

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<label for="age">Age:</label>

<input type="number" id="age" name="age" required min="1"><br><br>

<input type="submit" value="Register">

</form>

</body>

</html>

2.Create a file named submit.php to handle the form submission.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = trim($_POST['name']);
$email = trim($_POST['email']);

$age = intval($_POST['age']);

$errors = [];

if (empty($name)) {

$errors[] = "Name is required.";

if (!filter_var($email, FILTER_VALIDATE_EMAIL))

$errors[] = "Invalid email format.";

if ($age < 1) {

$errors[] = "Age must be a positive number.";

if (count($errors) > 0) {

foreach ($errors as $error) {

echo "<p>$error</p>";

echo '<a href="register.php">Go back</a>';

} else

echo "<h2>Registration Successful!</h2>";

echo "<p>Name: $name</p>";

echo "<p>Email: $email</p>";

echo "<p>Age: $age</p>";

echo '<a href="register.php">Register another student</a>';

} else {

echo "Invalid request method.";

?>
Output:

10.Construct a php program for complaint registration form.

Description:

1.Complaint_form.php: This file contains a simple form that requests the user’s name, email, and
complaint details. It sends the data to submit_complaint.php when submites.

2.Submit_complaint.php: This script receives the submitted data and displays it in the page.

Program:

1.Create a program named complaint_form.php

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Complaint Registration</title>

</head>

<body>

<h2>Complaint Registration Form</h2>

<form action="submit_complaint.php" method="POST">

Name: <input type="text" name="name" required><br><br>

Email: <input type="email" name="email" required><br><br>

Complaint: <textarea name="complaint" required></textarea><br><br>

<input type="submit" value="Register Complaint">

</form>

</body>

</html>

2.Create a program named submit_complaint.php.

<?php

$name = $_POST['name'];

$email = $_POST['email'];

$complaint = $_POST['complaint'];

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Complaint Details</title>

</head>

<body>

<h2>Complaint Registration Details</h2>

<p><strong>Name:</strong><?php echo $name; ?></p>


<p><strong>Email:</strong><?php echo $email; ?></p>

<p><strong>Complaint:</strong><?php echo nl2br($complaint); ?></p>

</body>

</html>

Output:

11.Construct a program to handle various exceptional handling in php.

Description

1. Custom Exception Classes:


o DivisionByZeroException for division by zero errors.

o InvalidInputException for cases where non-numeric input is provided.

2. Function divide():

o Checks if the numerator and denominator are numeric.

o Throws an InvalidInputException if either is not a number.

o Throws a DivisionByZeroException if the denominator is zero.

o Returns the result of the division if all conditions are met.

3. Try-Catch Block:

o The try block attempts to divide two numbers.

o The catch blocks handle different types of exceptions, providing specific error messages.

o A general Exception catch is included to handle any other unforeseen exceptions.

4. Finally Block:

o The finally block ensures that "Execution complete." is printed, regardless of whether an
exception occurred.

Program:

<?php

class DivisionByZeroException extends Exception {}

class InvalidInputException extends Exception {}

function divide($numerator, $denominator) {

if (!is_numeric($numerator) || !is_numeric($denominator)) {

throw new InvalidInputException("Both numerator and denominator must be numbers.");

if ($denominator == 0) {

throw new DivisionByZeroException("Cannot divide by zero.");

return $numerator / $denominator;

try {

$numerator = 10;

$denominator = 0;

$result = divide($numerator, $denominator);


echo "Result:".$result."\n";

} catch (DivisionByZeroException $e) {

echo "Error:".$e->getMessage() . "\n";

} catch (InvalidInputException $e) {

echo "Error:".$e->getMessage() . "\n";

} catch (Exception $e) {

echo "General Error:".$e->getMessage() . "\n";

} finally {

echo "Execution complete.\n";

Output:

?>

12. Construct a PHP program for sending and receiving Emails.

Description

· Sending emails: Using PHPMailer is a better option than PHP's built-in mail() function as it provides
more features, security, and reliability.

· Receiving emails: Use the IMAP protocol with the PHP IMAP extension to fetch and read emails from a
mail server.

1. Simple Sending Email Program Using mail() Function:

<?php
$to = '[email protected]';

$subject = 'Simple Email Test';

$message = 'Hello! This is a simple email test.';$headers = 'From: [email protected]'."\r\


n".'Reply-To:[email protected]'."\r\n".

'X-Mailer:PHP/'.phpversion();

if (mail($to, $subject, $message, $headers))

echo 'Email successfully sent!';

else

echo 'Email sending failed.';

?>

2. Basic Code for Receiving Emails Using IMAP (server configuration needed):

<?php

$hostname = '{imap.example.com:993/imap/ssl}INBOX';

$username = '[email protected]';

$password = 'your-email-password';

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to the mail


server:'.imap_last_error());

$emails = imap_search($inbox,'ALL');

if ($emails)

$latest_email = max($emails);

$overview = imap_fetch_overview($inbox,$latest_email,0);

$message = imap_fetchbody($inbox,$latest_email,1);

echo "Subject: {$overview[0]->subject}\n";

echo "From: {$overview[0]->from}\n";

echo "Message: {$message}\n";

}
else

echo 'No emails found.';

imap_close($inbox);

?>

13. Construct a PHP Program to maintain the number of visits of the user using Cookies.

Description

· Cookie Check: The script checks if the visit_count cookie exists. If it does, the value is incremented. If
not, it starts with 1.

· Setting the Cookie: The setcookie() function is used to set/update the cookie with the current visit
count. The expiration is set to 30 days.

· Output: The program outputs a welcome message and the number of times the user has visited the
page.

Program:

<?php

$cookie_expiration_time = time() + (30 * 24 * 60 * 60);

if(isset($_COOKIE['user_visits']))

$visits = $_COOKIE['user_visits'] + 1;

setcookie('user_visits', $visits, $cookie_expiration_time);

echo "Welcome back! You have visited this page $visits times.";

else

$visits = 1;

setcookie('user_visits', $visits, $cookie_expiration_time);

echo "This is your first visit! Welcome!";

?>
Output:

14. Construct a simple online shopping cart application using PHP. Using sessions, maintain a user's
shopping cart across multiple pages, even if they close the browser and return later.

Description

· Products Page: Display available products with the option to add them to the cart.

· Cart Page: Display the items added to the cart, with options to remove items or update quantities.

· Session Management: Use PHP sessions to maintain the cart state across multiple pages and store the
cart data even if the user leaves and returns later (by using sessions combined with cookies).

Product Page (products.php)

<?php

session_start();

if (!isset($_SESSION['cart']))

$_SESSION['cart'] = [];

$products = ['Product 1','Product 2','Product 3'];

if (isset($_POST['add']))

$product = $_POST['product'];

$_SESSION['cart'][] = $product;

echo "Added $product to the cart!";

}
?>

<h1>Products</h1>

<form method="post">

<ul>

<?php foreach ($products as $product):?>

<li>

<?php echo $product;?>

<input type="hidden" name="product" value="<?php echo $product; ?>">

<button type="submit" name="add">Add to Cart</button>

</li>

<?php endforeach; ?>

</ul>

</form>

<p><a href="cart.php">View Cart</a></p>

2. Cart Page (cart.php)

<?php

session_start();

if (isset($_POST['clear']))

$_SESSION['cart'] = [];

echo "Cart cleared!";

?>

<h1>Your Cart</h1>

<ul>

<?php if (!empty($_SESSION['cart'])): ?>

<?php foreach ($_SESSION['cart'] as $item): ?>

<li><?php echo $item; ?></li>

<?php endforeach; ?>

<?php else: ?>


<li>Your cart is empty.</li>

<?php endif; ?>

</ul>

<form method="post">

<button type="submit" name="clear">Clear Cart</button>

</form>

<p><a href="products.php">Back to Products</a></p>

Output:

15. Write a simple PHP program on Introspection and Serialization


Description:

Introspection in PHP refers to the ability of the program to inspect classes, objects, and interfaces to find
out what properties and methods they have at runtime.

Serialization is the process of converting an object into a string representation so that it can be stored or
transmitted, and then later reconstructed back into its original object form.

Program

<?php

public $brand; public $model;

public function __construct($brand, $model)

$this->brand = $brand;

$this->model = $model;

public function displayInfo()

return "This car is a $this->brand $this->model.";

$myCar = new Car("Toyota", "Corolla");

echo "Class Name: " . get_class($myCar) . "<br>";

echo "Does displayInfo method exist? " . (method_exists($myCar, 'displayInfo') ? 'Yes' : 'No') . "<br>";

$serializedCar = serialize($myCar);

echo "Serialized Object: $serializedCar<br>";

$unserializedCar = unserialize($serializedCar);

echo "After Unserialization: " . $unserializedCar->displayInfo() . "<br>";

?>

You might also like