📝 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" + 3 → 52 + 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
| Feature | mysqli | PDO |
|---|---|---|
| DB Support | MySQL only | Multiple DBs |
| Security | Good | Better (prepared statements) |
| Flexibility | Low | High |
👉 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






