complete step-by-step solution code

🟢 Step 1: Project Setup

mkdir composer-exam
cd composer-exam
composer init -y

Install packages:

composer require monolog/monolog
composer require guzzlehttp/guzzle
composer require phpmailer/phpmailer

🟢 Step 2: Folder Structure

composer-exam/

├── composer.json
├── vendor/
├── index.php
├── logger.php
├── api.php
├── mail.php
├── src/
│ └── User.php
├── logs/
│ └── app.log

🟡 Step 3: Logger System (logger.php)

<?php require 'vendor/autoload.php';use Monolog\Logger;
use Monolog\Handler\StreamHandler;// Create log channel
$log = new Logger('app');// Create logs directory if not exists
if (!file_exists('logs')) {
    mkdir('logs', 0777, true);
}// Add handler
$log->pushHandler(new StreamHandler('logs/app.log', Logger::DEBUG));// Logs
$log->info('User visited site');
$log->warning('Invalid login attempt');
$log->error('System failure');echo "Logs created successfully!";

🟡 Step 4: API Integration (api.php)

<?php require 'vendor/autoload.php';use GuzzleHttp\Client;$client = new Client();try {
    $response = $client->request('GET', 'https://jsonplaceholder.typicode.com/users');    $data = json_decode($response->getBody(), true);    echo "<h3>First 3 Users:</h3>";    for ($i = 0; $i < 3; $i++) {
        echo "Name: " . $data[$i]['name'] . "<br>";
        echo "Email: " . $data[$i]['email'] . "<br><br>";
    }} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

🟠 Step 5: Email System (mail.php)

<?php require 'vendor/autoload.php';use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;$mail = new PHPMailer(true);try {
    // SMTP Settings (example: Gmail)
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your_email@gmail.com';
    $mail->Password   = 'your_app_password'; // Use App Password
    $mail->SMTPSecure = 'tls';
    $mail->Port       = 587;    // Email settings
    $mail->setFrom('your_email@gmail.com', 'Test');
    $mail->addAddress('test@example.com');    $mail->Subject = 'Test Mail';
    $mail->Body    = 'Hello from Composer';    $mail->send();
    echo "Email sent successfully!";} catch (Exception $e) {
    echo "Mailer Error: {$mail->ErrorInfo}";
}

🔴 Step 6: PSR-4 Autoloading

Update composer.json

{
"require": {
"monolog/monolog": "^3.0",
"guzzlehttp/guzzle": "^7.0",
"phpmailer/phpmailer": "^6.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}

Run:

composer dump-autoload

Create Class: src/User.php

<?php namespace App;class User {
    public function getName() {
        return "Aditya";
    }
}

Use in index.php

<?php require 'vendor/autoload.php';use App\User;$user = new User();echo $user->getName();

🔴 Step 7: Mini Project (Contact Form)

👉 form.html

<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body><form method="POST" action="contact.php">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Message: <textarea name="message" required></textarea><br><br>
<button type="submit">Send</button>
</form></body>
</html>

👉 contact.php

<?php require 'vendor/autoload.php';use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use PHPMailer\PHPMailer\PHPMailer;// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];// Validate
if (empty($name) || empty($email) || empty($message)) {
    die("All fields are required!");
}// Logger
$log = new Logger('contact');
$log->pushHandler(new StreamHandler('logs/app.log', Logger::INFO));
$log->info("Contact form submitted by: $email");// Send Email
$mail = new PHPMailer(true);try {
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_email@gmail.com';
    $mail->Password = 'your_app_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;    $mail->setFrom($email, $name);
    $mail->addAddress('your_email@gmail.com');    $mail->Subject = 'New Contact Message';
    $mail->Body = "Name: $name\nEmail: $email\nMessage: $message";    $mail->send();    echo "Message sent successfully!";} catch (Exception $e) {
    echo "Error: {$mail->ErrorInfo}";
}

🧠 Step 8: Restore Project (Important)

👉 If vendor/ deleted:

composer install

✅ Final Output Checklist

✔ Logs created
✔ API data fetched
✔ Email working
✔ Autoload working
✔ Contact form working


🚀 Pro Tips (Real Industry)

  • Use .env for email credentials
  • Never hardcode passwords
  • Always validate user input
  • Use MVC structure for large apps

Coding-Based Practical Exam (Real-World Level)

💻 Practical Exam: Composer & PHP Packages

⏱ Duration: 2–3 Hours

🎯 Objective: Test real-world Composer usage


🟢 Section A: Setup (Basic – 10 Marks)

✅ Task 1:

  • Create a new project folder: composer-exam
  • Initialize Composer:
composer init

✅ Task 2:

  • Install these packages:
composer require monolog/monolog
composer require guzzlehttp/guzzle
composer require phpmailer/phpmailer

👉 Evaluation:

  • composer.json created ✔
  • vendor/ folder exists ✔

🟡 Section B: Logging System (20 Marks)

✅ Task:

Create a file: logger.php

👉 Requirements:

  • Use Monolog
  • Log messages into logs/app.log
  • Add:
    • INFO → “User visited site”
    • WARNING → “Invalid login attempt”
    • ERROR → “System failure”

👉 Expected Skills:

  • Autoload usage
  • Package integration

🟡 Section C: API Integration (20 Marks)

✅ Task:

Create api.php

👉 Requirements:

  • Use Guzzle
  • Fetch data from:
https://jsonplaceholder.typicode.com/users

👉 Output:

  • Display:
    • Name
    • Email
  • Show only first 3 users

👉 Bonus:

  • Handle API error (try-catch)

🟠 Section D: Email System (20 Marks)

✅ Task:

Create mail.php

👉 Requirements:

  • Use PHPMailer
  • Send test email

Fields:

👉 Bonus:

  • Use SMTP configuration

🔴 Section E: Autoloading (15 Marks)

✅ Task:

Implement PSR-4 Autoloading

👉 Step 1: Update composer.json

{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}

👉 Step 2:

composer dump-autoload

👉 Step 3:
Create:

📁 src/User.php

namespace App;class User {
public function getName() {
return "Aditya";
}
}

👉 Step 4:
Use it in index.php


🔴 Section F: Mini Project (15 Marks)

✅ Build: Simple Contact Form System

👉 Requirements:

  • HTML form:
    • Name
    • Email
    • Message
  • On submit:
    • Log request (Monolog)
    • Send email (PHPMailer)

👉 Bonus:

  • Validate inputs

🧠 Section G: Debugging (Bonus – 10 Marks)

Scenario:

  • Delete vendor/ folder

👉 Task:

  • Restore project using Composer

✔ Expected command:

composer install

📊 Marking Scheme

SectionMarks
Setup10
Logging20
API20
Email20
Autoloading15
Mini Project15
Bonus10

🎯 Evaluation Criteria

  • ✔ Proper Composer usage
  • ✔ Clean code
  • ✔ Error handling
  • ✔ File structure
  • ✔ Real-world logic

📁 Expected Folder Structure

composer-exam/

├── composer.json
├── vendor/
├── index.php
├── logger.php
├── api.php
├── mail.php
├── src/
│ └── User.php
├── logs/
│ └── app.log

🚀 Pro-Level Challenge (Optional)

👉 Add:

  • .env file for config
  • Use vlucas/phpdotenv

exam-level MCQ test for Composer & Packages (PHP)

📝 Composer MCQ Test (PHP)

🔹 Section A: Basic Concepts

1. What is Composer in PHP?
A. PHP Framework
B. Dependency Manager
C. Database Tool
D. Web Server
👉 Answer: B


2. Which file is used to define dependencies in Composer?
A. index.php
B. config.php
C. composer.json
D. package.json
👉 Answer: C


3. Which command initializes a Composer project?
A. composer start
B. composer create
C. composer init
D. composer new
👉 Answer: C


4. Which command installs dependencies from composer.json?
A. composer require
B. composer install
C. composer update
D. composer load
👉 Answer: B


5. What folder stores installed packages?
A. packages/
B. libs/
C. vendor/
D. modules/
👉 Answer: C


🔹 Section B: Commands & Usage

6. Which command adds a new package?
A. composer install
B. composer require
C. composer add
D. composer get
👉 Answer: B


7. Which command updates all dependencies?
A. composer upgrade
B. composer refresh
C. composer update
D. composer reload
👉 Answer: C


8. What does this command do?

composer remove monolog/monolog

A. Installs package
B. Updates package
C. Deletes package
D. Runs package
👉 Answer: C


9. What is the purpose of composer.lock?
A. Lock files from editing
B. Store exact versions of dependencies
C. Backup file
D. Cache file
👉 Answer: B


10. Which command regenerates autoload files?
A. composer reload
B. composer autoload
C. composer dump-autoload
D. composer refresh
👉 Answer: C


🔹 Section C: Autoloading

11. Which file enables autoloading?
A. autoload.php
B. vendor/autoload.php
C. load.php
D. init.php
👉 Answer: B


12. What is PSR-4?
A. PHP Server Rule
B. Coding standard for autoloading
C. Database format
D. API protocol
👉 Answer: B


13. Which keyword is used with namespaces?
A. import
B. include
C. use
D. require
👉 Answer: C


14. What does this line do?

require 'vendor/autoload.php';

A. Connects database
B. Loads all dependencies automatically
C. Runs Composer
D. Installs packages
👉 Answer: B


🔹 Section D: Practical Understanding

15. Difference between install and update?
A. No difference
B. Install uses lock file, update upgrades versions
C. Update installs packages
D. Install deletes packages
👉 Answer: B


16. Which package is used for sending emails?
A. Guzzle
B. Monolog
C. PHPMailer
D. PHPUnit
👉 Answer: C


17. Which package is used for HTTP requests?
A. Monolog
B. Guzzle
C. PHPMailer
D. Slim
👉 Answer: B


18. Monolog is used for?
A. Email
B. Logging
C. Database
D. Routing
👉 Answer: B


🔹 Section E: Advanced

19. What will happen if vendor folder is deleted?
A. Project stops working
B. Composer breaks permanently
C. Can be restored using composer install
D. Nothing happens
👉 Answer: C


20. Which version constraint means “compatible with version 6.x”?
A. “6.0”
B. “^6.0”
C. “~6.0”
D. “>=6.0”
👉 Answer: B


🎯 Bonus (Case-Based Question)

21. You cloned a project from GitHub. What should you run first?
A. composer update
B. composer require
C. composer install
D. composer init
👉 Answer: C


📊 Scoring Guide

  • 18–21 → 🟢 Excellent
  • 14–17 → 🟡 Good
  • 10–13 → 🟠 Average
  • <10 → 🔴 Needs Practice

hands-on practice exercises for Composer & Packages (PHP)

🧪 Composer Practice Exercises (PHP)

🟢 Level 1: Basics (Beginner)

✅ Exercise 1: Install Composer

  • Install Composer on your system
  • Run:
composer -v

👉 Output should show version


✅ Exercise 2: Create First Project

  • Create a new folder composer-practice
  • Run:
composer init
  • Fill details (name, description, etc.)

👉 Check: composer.json created


✅ Exercise 3: Install First Package

Install a simple package:

composer require monolog/monolog

👉 Task:

  • Open composer.json
  • Verify package added
  • Check vendor/ folder

🟡 Level 2: Usage (Intermediate)

✅ Exercise 4: Use Installed Package

👉 Create index.php

<?php
require 'vendor/autoload.php';use Monolog\Logger;
use Monolog\Handler\StreamHandler;$log = new Logger('app');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));$log->warning('This is a warning!');
$log->error('This is an error!');

👉 Task:

  • Run file
  • Check app.log created

✅ Exercise 5: Install PHPMailer

composer require phpmailer/phpmailer

👉 Task:

  • Create a PHP script to send email
  • (Use dummy SMTP if needed)

✅ Exercise 6: Remove Package

composer remove monolog/monolog

👉 Task:

  • Check:
    • composer.json
    • vendor/

🟠 Level 3: Autoloading

✅ Exercise 7: Manual vs Autoload

👉 Without Composer:

  • Create 3 PHP class files
  • Include using require

👉 With Composer:

  • Use:
require 'vendor/autoload.php';

👉 Task:

  • Compare code length and readability

✅ Exercise 8: PSR-4 Autoload

👉 Step 1: Update composer.json

{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}

👉 Step 2:

composer dump-autoload

👉 Step 3: Create class

📁 src/User.php

<?php
namespace App;class User {
public function sayHello() {
return "Hello User!";
}
}

👉 Step 4: Use it

<?php
require 'vendor/autoload.php';use App\User;$user = new User();
echo $user->sayHello();

🔴 Level 4: Real-World Practice

✅ Exercise 9: Build Logger System

👉 Task:

  • Use Monolog
  • Create logs for:
    • Login success
    • Login failure
    • Errors

✅ Exercise 10: API Integration

👉 Task:

  • Install:
composer require guzzlehttp/guzzle
  • Fetch data from:
https://jsonplaceholder.typicode.com/posts

👉 Display:

  • First 5 posts

✅ Exercise 11: Mini Project (Important)

👉 Build: Simple Contact Form System

Requirements:

  • Use PHPMailer (via Composer)
  • Form fields:
    • Name
    • Email
    • Message
  • Send email on submit

🧠 Bonus Challenges (Advanced)

🚀 Challenge 1:

Create your own PHP package and install it using Composer locally


🚀 Challenge 2:

  • Add version constraints in composer.json
  • Try:
"phpmailer/phpmailer": "^6.0"

👉 Test:

  • Run composer update

🚀 Challenge 3:

  • Delete vendor/
  • Run:
composer install

👉 Understand:

  • Difference between install vs update

🎯 Tip (For You)

  • 🧪 1 task per day

16. Composer & Packages (PHP)

🔹 What is Composer?

Composer is a dependency manager for PHP.

👉 Simple meaning:
It helps you install, manage, and update external libraries (packages) in your PHP project.

💡 Example:
Instead of writing everything from scratch, you can install ready-made libraries like:

  • Payment gateways
  • Email sending (PHPMailer)
  • PDF generation
  • APIs integration

👉 Composer does this automatically.


🔹 Why Composer is Important?

Without Composer ❌

  • Manually download files
  • Handle dependencies yourself
  • Difficult updates

With Composer ✅

  • One command installs everything
  • Automatically loads files
  • Easy updates

🔹 Installing Composer

Step 1: Download Composer

Go to:
👉 https://getcomposer.org/

Step 2: Install

For Windows:

  • Download Composer-Setup.exe
  • Install normally

Check installation:

composer -v

If version shows → Installed successfully ✅


🔹 Composer Basic Commands

1. Initialize project

composer init

2. Install dependencies

composer install

3. Add a package

composer require monolog/monolog

4. Update packages

composer update

🔹 Installing Libraries (Packages)

👉 Example: Install PHPMailer

composer require phpmailer/phpmailer

Composer will:

  • Download package
  • Create vendor/ folder
  • Update composer.json
  • Generate autoload file

🔹 composer.json File

This is the main file for Composer.

Example:

{
"require": {
"phpmailer/phpmailer": "^6.0"
}
}

👉 It stores:

  • Project dependencies
  • Version control

🔹 Autoloading (Very Important)

Composer provides automatic class loading.

👉 Instead of:

require 'file1.php';
require 'file2.php';
require 'file3.php';

👉 Use:

require 'vendor/autoload.php';

Now all classes are automatically loaded ✅


🔹 Example Usage

<?phprequire 'vendor/autoload.php';use PHPMailer\PHPMailer\PHPMailer;$mail = new PHPMailer();
$mail->setFrom('test@example.com', 'Test');
$mail->addAddress('user@example.com');
$mail->Subject = 'Hello';
$mail->Body = 'This is a test email';$mail->send();

🔹 PSR-4 Autoloading (Advanced)

You can define your own classes:

{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}

Then run:

composer dump-autoload

Now you can use:

use App\Controllers\UserController;

🔹 Folder Structure After Composer

project/

├── composer.json
├── composer.lock
├── vendor/
│ ├── autoload.php
│ └── packages...

🔥 Interview Questions

  • What is Composer in PHP?
  • Difference between require and require_once vs Composer autoload?
  • What is composer.json?
  • What is PSR-4?
  • Difference between install and update?

Detailed Answer Sheet (Advanced Solutions)

📝 Advanced PHP – Answer Sheet


📘 Section A – MCQs (Detailed Explanation)

1. ✅ A – 15

PHP converts "10abc"10 (type juggling), then 10 + 5 = 15.


2. ✅ C – prepare() (PDO)

Prepared statements prevent SQL Injection by separating query & data.


3. ✅ A – true

Empty array [] is considered false in loose comparison (==).


4. ✅ B – echo

echo is faster because it is not a function (no return value).


5. ✅ B – Local but retains value

function test() {
static $x = 0;
$x++;
echo $x;
}

Value persists between calls.


6. ✅ B – Runs always

finally executes whether exception occurs or not.


7. ✅ B – 10

Operator precedence:
"5".2"52""52" + 352 + 3 = 55

👉 But PHP evaluates + before . in this case → result = 10 (important tricky behavior)


8. ✅ C – register_shutdown_function()

Used to catch fatal errors indirectly.


9. ✅ D – None

All superglobals can be modified (though not recommended).


10. ✅ B – Enforces strict typing

Prevents automatic type conversion.


📗 Section B – Analytical Answers


1. mysqli vs PDO

FeaturemysqliPDO
DB SupportMySQL onlyMultiple DBs
SecurityGoodBetter (prepared statements)
FlexibilityLowHigh

👉 Real-world: Use PDO for scalable apps.


2. "0" == false

PHP uses loose comparison:

"0" == false → true

Because "0" converts to integer 0.

👉 Avoid using ==, use ===.


3. Type Juggling

echo "5" + 2; // 7
echo "abc" + 5; // 5

PHP automatically converts types.

👉 Dangerous → Use strict typing.


4. Closures

Anonymous functions:

$sum = function($a, $b) {
return $a + $b;
};

👉 Use case:

  • Callbacks
  • Middleware
  • Functional programming

5. Error vs Exception vs Throwable

Throwable
├── Exception
└── Error
  • Error → system-level (fatal)
  • Exception → application-level
  • Throwable → base interface

📙 Section C – Programming Solutions


✅ Q1. Secure Login System

<?php
session_start();
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");// User input
$email = $_POST['email'];
$password = $_POST['password'];// Fetch user
$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();if ($user && password_verify($password, $user['password'])) {
$_SESSION['user'] = $user['email'];
echo "Login successful";
} else {
echo "Invalid credentials";
}
?>

👉 Uses:

  • password_hash()
  • password_verify()
  • Prepared statements

✅ Q2. REST API

<?php
header("Content-Type: application/json");try {
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
throw new Exception("Only GET allowed");
} $data = ["status" => "success", "data" => [1,2,3]];
echo json_encode($data);} catch (Exception $e) {
http_response_code(400);
echo json_encode(["error" => $e->getMessage()]);
}
?>

✅ Q3. File Upload

<?php
$file = $_FILES['file'];if ($file['size'] > 2*1024*1024) {
die("File too large");
}$allowed = ['image/jpeg', 'image/png'];
if (!in_array($file['type'], $allowed)) {
die("Invalid file type");
}move_uploaded_file($file['tmp_name'], "uploads/" . $file['name']);
echo "Uploaded successfully";
?>

✅ Q4. Custom Error Handling System

<?php
set_error_handler(function($errno, $errstr) {
throw new ErrorException($errstr, 0, $errno);
});try {
echo $undefined; // error → exception
} catch (Throwable $e) {
error_log($e->getMessage(), 3, "error.log");
echo "Something went wrong!";
}
?>

💻 Section D – Case Study Solution


1. White Screen Debugging

  • Enable errors:
ini_set('display_errors', 1);
error_reporting(E_ALL);
  • Check logs
  • Fix syntax/fatal errors

2. Performance Optimization

  • Use caching (Redis, OPcache)
  • Optimize queries
  • Use CDN
  • Minimize loops

3. Database Failure Handling

try {
$pdo = new PDO(...);
} catch (Exception $e) {
error_log($e->getMessage());
}
  • Retry mechanism
  • Fallback message

4. Complete Error Strategy

  • Disable display in production
  • Log all errors
  • Use try-catch
  • Centralized logging system
  • Monitoring tools

🏆 Bonus – Mini MVC Structure

// index.php (Router)
$url = $_GET['url'] ?? 'home';
require "controllers/$url.php";
// controller
$data = ["name" => "Aditya"];
require "views/home.php";
// view
echo $data['name'];

🎯 High-Level Scoring Tips

✔ Use strict types
✔ Always use prepared statements
✔ Handle all errors properly
✔ Write modular code (MVC)
✔ Think like a backend developer

Advanced University-Level PHP Exam Paper (Tough Level)

📝 Advanced PHP Exam Paper (Tough Level)

Subject: Advanced PHP Programming
Time: 3 Hours
Maximum Marks: 100


📘 Section A – Advanced MCQs (10 × 2 = 20 Marks)

  1. What will be the output?
$a = "10abc";
$b = 5;
echo $a + $b;

A) 15
B) 105
C) Error
D) 10abc5
✅ Answer: A


  1. Which function prevents SQL Injection?
    A) mysqli_query()
    B) htmlspecialchars()
    C) prepare() (PDO)
    D) echo()
    ✅ Answer: C

  1. What is the output?
var_dump([] == false);

A) true
B) false
C) error
D) null
✅ Answer: A


  1. Which is fastest output method?
    A) print
    B) echo
    C) printf
    D) var_dump
    ✅ Answer: B

  1. What is the scope of a static variable inside function?
    A) Global
    B) Local but retains value
    C) Block only
    D) Session
    ✅ Answer: B

  1. What does finally guarantee?
    A) Runs only if no error
    B) Runs always
    C) Runs on fatal error only
    D) Skips execution
    ✅ Answer: B

  1. Output?
echo "5" . 2 + 3;

A) 523
B) 10
C) 55
D) Error
✅ Answer: B


  1. Which handles fatal errors indirectly?
    A) try-catch
    B) set_error_handler()
    C) register_shutdown_function()
    D) error_reporting()
    ✅ Answer: C

  1. Which superglobal is immutable?
    A) $_POST
    B) $_GET
    C) $_SERVER
    D) None
    ✅ Answer: D

  1. What does strict_types=1 do?
    A) Converts types automatically
    B) Enforces strict type checking
    C) Disables errors
    D) Improves speed
    ✅ Answer: B

📗 Section B – Analytical Questions (5 × 4 = 20 Marks)

  1. Explain the difference between mysqli and PDO with real-world usage.
  2. Analyze:
if ("0" == false) echo "Yes";

Why does this happen?

  1. Explain how PHP handles type juggling with examples.
  2. What are closures in PHP? Give a real use case.
  3. Explain error vs exception vs throwable with hierarchy.

📙 Section C – Long Programming Questions (4 × 10 = 40 Marks)


✅ Q1. Build a secure login system with:

  • Password hashing
  • Session handling
  • Input validation

✅ Q2. Create a REST API in PHP:

  • Return JSON
  • Handle GET request
  • Include error handling

✅ Q3. Write a PHP script to:

  • Upload file
  • Validate type & size
  • Handle errors

✅ Q4. Create a custom error handling system:

  • Convert errors to exceptions
  • Log errors to file
  • Show user-friendly message

💻 Section D – Case Study (1 × 20 = 20 Marks)

🔥 Scenario:

Your PHP website is:

  • Showing white screen
  • Users report slow performance
  • Database queries sometimes fail

Questions:

  1. How will you debug the white screen issue?
  2. How will you optimize performance?
  3. How will you handle database failures?
  4. Suggest a complete error-handling strategy.

🏆 Bonus (Optional – 10 Marks)

Build a mini MVC structure in PHP:

  • Routing
  • Controller
  • View
  • Error handling

🎯 Examiner Expectations (High-Level)

  • Clean architecture (MVC mindset)
  • Secure coding (XSS, SQL Injection)
  • Proper error handling
  • Use of modern PHP (PDO, exceptions)
  • Real-world thinking

🔥 Difficulty Level

SectionLevel
MCQMedium
AnalyticalHard
CodingVery Hard
Case StudyExpert

Detailed Answer Sheet (Solutions)

📝 PHP Exam – Answer Sheet


📘 Section A – MCQ Answers (with explanation)

  1. B – Hypertext Preprocessor
    → Official recursive name of PHP.
  2. B – $
    → All PHP variables start with $.
  3. C – Both
    echo and print both output text (echo is faster).
  4. C – Fatal Error
    → Stops execution immediately.
  5. B – $_POST
    → Used to collect form data (POST method).
  6. B – mysqli_connect()
    → Procedural way to connect MySQL.
  7. B – Variable exists
    → Checks if variable is set and not null.
  8. D – All
    try, catch, throw are used in exception handling.
  9. B – session_start()
    → Initializes session.
  10. C – .php
    → Default extension.

📗 Section B – Short Answers

1. What is PHP?

PHP is a server-side scripting language used to build dynamic web applications.


2. GET vs POST

GETPOST
Data in URLData in body
Less secureMore secure
Limited sizeLarge data

3. Session

A session stores user data on the server across multiple pages.


4. Cookie

A cookie stores small data on the user’s browser.


5. Array

An array stores multiple values in one variable.

$arr = ["A", "B", "C"];

6. Error Handling

Process of detecting and managing errors in PHP scripts.


7. include vs require

includerequire
Warning if file missingFatal error
Script continuesScript stops

8. Function

Reusable block of code.

function test() {
echo "Hello";
}

9. $_SERVER

Superglobal containing server/environment info.


10. PDO

PHP Data Objects – secure database access using prepared statements.


📙 Section C – Long Answers

1. PHP Data Types

  • String → "Hello"
  • Integer → 10
  • Float → 10.5
  • Boolean → true/false
  • Array → [1,2,3]
  • Object → Class instance
  • NULL → empty variable

2. Loops in PHP

// for
for ($i=0; $i<5; $i++) {
echo $i;
}// while
$i = 0;
while ($i < 5) {
echo $i;
$i++;
}// foreach
$arr = [1,2,3];
foreach ($arr as $val) {
echo $val;
}

3. Form Handling

<form method="post">
<input type="text" name="name">
<input type="submit">
</form><?php
if ($_POST) {
echo $_POST['name'];
}
?>

4. Error Handling

try {
throw new Exception("Error occurred");
} catch (Exception $e) {
echo $e->getMessage();
}

Also:

  • error_reporting()
  • set_error_handler()

5. Session & Cookie

// Session
session_start();
$_SESSION['user'] = "Aditya";// Cookie
setcookie("user", "Aditya", time()+3600);

💻 Section D – Practical Solutions


✅ Q1. Even/Odd

$num = 10;if ($num % 2 == 0) {
echo "Even";
} else {
echo "Odd";
}

✅ Q2. Form Handling

<form method="post">
<input type="text" name="name">
<input type="submit">
</form><?php
if ($_POST) {
echo htmlspecialchars($_POST['name']);
}
?>

👉 htmlspecialchars() prevents XSS (important improvement)


✅ Q3. Database Connection

$conn = mysqli_connect("localhost", "root", "", "test");if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}echo "Connected successfully";

✅ Q4. Exception Handling

try {
if (!file_exists("test.txt")) {
throw new Exception("File not found");
}
} catch (Exception $e) {
echo $e->getMessage();
}

🏆 Bonus Solution – Login System

session_start();if ($_POST) {
$user = $_POST['username'];
$pass = $_POST['password']; if ($user == "admin" && $pass == "1234") {
$_SESSION['user'] = $user;
echo "Login successful";
} else {
echo "Invalid credentials";
}
}

🎯 Extra Examiner Notes (High Scoring Tips)

✔ Use input validation & sanitization
✔ Prefer PDO over mysqli (security)
✔ Always handle errors properly
✔ Avoid showing raw errors in production
✔ Write clean, readable code

Complete PHP Exam Paper (Theory + Practical)

👇


📝 Full PHP Exam Paper

Subject: PHP Programming
Time: 3 Hours
Maximum Marks: 100


📘 Section A – Objective (MCQs)

(10 × 1 = 10 Marks)

  1. PHP stands for:
    A) Personal Home Page
    B) Hypertext Preprocessor
    C) Private Home Page
    D) Preprocessor Home Page
    ✅ Answer: B
  2. Which symbol is used for variables in PHP?
    A) #
    B) $
    C) @
    D) &
    ✅ Answer: B
  3. Which function outputs text?
    A) print()
    B) echo()
    C) Both
    D) None
    ✅ Answer: C
  4. Which error stops execution?
    A) Warning
    B) Notice
    C) Fatal Error
    D) Info
    ✅ Answer: C
  5. Which superglobal is used for form data?
    A) $_FORM
    B) $_POST
    C) $_DATA
    D) $_INPUT
    ✅ Answer: B
  6. Which function connects to MySQL (procedural)?
    A) connect_db()
    B) mysqli_connect()
    C) db_connect()
    D) mysql_link()
    ✅ Answer: B
  7. What does isset() check?
    A) Empty value
    B) Variable exists
    C) Data type
    D) Output
    ✅ Answer: B
  8. Which keyword is used for exception?
    A) catch
    B) throw
    C) try
    D) All
    ✅ Answer: D
  9. Which function is used for sessions?
    A) session_create()
    B) session_start()
    C) session_open()
    D) start_session()
    ✅ Answer: B
  10. Default file extension of PHP?
    A) .html
    B) .js
    C) .php
    D) .xml
    ✅ Answer: C

📗 Section B – Short Answer

(10 × 2 = 20 Marks)

  1. What is PHP?
  2. Difference between GET and POST
  3. What is a session?
  4. What is a cookie?
  5. Define array in PHP
  6. What is error handling?
  7. What is include vs require?
  8. What is a function?
  9. What is $_SERVER?
  10. What is PDO?

📙 Section C – Long Answer

(5 × 6 = 30 Marks)

  1. Explain PHP data types with examples
  2. Explain loops in PHP (for, while, foreach)
  3. Explain form handling with example
  4. Explain error handling in PHP
  5. Explain session and cookie with examples

💻 Section D – Practical / Coding

(4 × 10 = 40 Marks)


✅ Q1. Write a PHP program to check even or odd number.

<?php
$num = 10;if ($num % 2 == 0) {
echo "Even Number";
} else {
echo "Odd Number";
}
?>

✅ Q2. Create a form and display submitted data.

<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form><?php
if ($_POST) {
echo "Name: " . $_POST['name'];
}
?>

✅ Q3. Connect to MySQL database.

<?php
$conn = mysqli_connect("localhost", "root", "", "test");if (!$conn) {
die("Connection failed");
}
echo "Connected successfully";
?>

✅ Q4. Exception Handling Example

<?php
try {
if (!file_exists("test.txt")) {
throw new Exception("File not found");
}
} catch (Exception $e) {
echo $e->getMessage();
}
?>

🏆 Bonus Question (Optional – 10 Marks)

Create a login system using:

  • Form
  • Session
  • Validation

📊 Marking Scheme

SectionMarks
A10
B20
C30
D40
Bonus10

🎯 Examiner Tips

  • Write clean syntax
  • Use comments in code
  • Handle errors properly
  • Show output clearly
  • Follow best practices

PHP Error Handling MCQ Test Paper (with Answers)

📝 PHP Error Handling – MCQ Test

📚 Section A: Basic (1 Mark Each)

1. Which function is used to report errors in PHP?
A) display_error()
B) error_reporting()
C) show_error()
D) report_error()
Answer: B


2. Which error type stops script execution?
A) Notice
B) Warning
C) Fatal Error
D) Deprecated
Answer: C


3. What does E_NOTICE indicate?
A) Critical error
B) Minor issue
C) Syntax error
D) Database error
Answer: B


4. Which function is used to display errors?
A) ini_set()
B) show_error()
C) print_error()
D) log_error()
Answer: A


5. What is the default behavior of warnings?
A) Stop script
B) Restart script
C) Continue execution
D) Delete file
Answer: C


📘 Section B: Intermediate (2 Marks Each)

6. Which block is used to handle exceptions?
A) if-else
B) try-catch
C) switch
D) loop
Answer: B


7. What keyword is used to throw an exception?
A) catch
B) throw
C) error
D) exception
Answer: B


8. Which class is used for exceptions in PHP?
A) Error
B) Exception
C) Throwable
D) Catch
Answer: B


9. What does Throwable represent?
A) Only errors
B) Only exceptions
C) Both errors and exceptions
D) None
Answer: C


10. What will happen if an exception is not caught?
A) Script continues
B) Script stops with error
C) Ignored
D) Page reloads
Answer: B


📙 Section C: Advanced (3 Marks Each)

11. Which function sets a custom error handler?
A) error_handler()
B) set_error_handler()
C) custom_error()
D) handle_error()
Answer: B


12. Which function generates a user-defined error?
A) user_error()
B) trigger_error()
C) throw_error()
D) error_create()
Answer: B


13. Which function logs errors to a file?
A) log_error()
B) error_log()
C) write_log()
D) file_log()
Answer: B


14. Which is used for debugging variables?
A) echo
B) print
C) var_dump()
D) show()
Answer: C


15. What is the purpose of finally block?
A) Catch error
B) Always execute code
C) Throw error
D) Stop script
Answer: B


🔥 Section D: Scenario-Based (4 Marks Each)

16. What will this code do?

echo 10/0;

A) Output 0
B) Fatal error
C) Warning/Error
D) Nothing
Answer: C


17. What is best practice in production?
A) Show errors
B) Hide errors and log them
C) Ignore errors
D) Stop execution
Answer: B


18. Which function handles fatal errors indirectly?
A) set_error_handler()
B) register_shutdown_function()
C) catch()
D) throw()
Answer: B


19. Which is better for database error handling?
A) echo
B) try-catch
C) print
D) die()
Answer: B


20. White screen of death means?
A) Syntax error
B) Hidden fatal error
C) Network issue
D) Browser crash
Answer: B


🏆 Score Guide

ScoreLevel
16–20Excellent 🔥
11–15Good 👍
6–10Average ⚠️
0–5Needs Improvement ❌