1. What does PHP stand for?
Difficulty: EasyType: MCQTopic: PHP Basics
- Personal Home Page
- Private Hypertext Processor
- PHP: Hypertext Preprocessor
- Public Hosting Program
PHP originally stood for Personal Home Page, but now it means PHP Hypertext Preprocessor. It is a recursive acronym and used mainly for server-side scripting.
Correct Answer: PHP: Hypertext Preprocessor
2. Which symbol is used to start a variable in PHP?
Difficulty: EasyType: MCQTopic: PHP Basics
In PHP, all variables begin with a dollar sign. For example, $name equals 'John'.
Correct Answer: $
Example Code
$name = 'John';
3. How do you write a single-line comment in PHP?
Difficulty: EasyType: MCQTopic: PHP Basics
- // comment
- # comment
- /* comment */
- Both A and B
PHP allows single-line comments using double slashes or a hash. Multiline comments use slash star and star slash.
Correct Answer: Both A and B
Example Code
// comment or # comment
4. Which statement is used to output text in PHP?
Difficulty: EasyType: MCQTopic: Output Basics
- print()
- echo
- printf()
- display()
The echo statement outputs text or variables. It is faster than print and can take multiple arguments.
Correct Answer: echo
Example Code
echo 'Hello World';
5. Which of the following is NOT a valid PHP data type?
Difficulty: MediumType: MCQTopic: Data Types
- Integer
- String
- Float
- Character
PHP does not have a specific 'character' type. A single character is treated as a string of length one.
Correct Answer: Character
6. Are variable names in PHP case-sensitive?
Difficulty: MediumType: MCQTopic: PHP Basics
- Yes
- No
- Only in classes
- Depends on configuration
PHP variable names are case-sensitive. $Name and $name are different variables. However, function names are not case-sensitive.
Correct Answer: Yes
7. Which function is used to define a constant in PHP?
Difficulty: MediumType: MCQTopic: Constants
- constant()
- const
- define()
- static()
define() is used to create a constant that cannot be changed once declared. Example: define('PI', 3.14).
Correct Answer: define()
Example Code
define('PI', 3.14);8. What will be the result of the expression 10 . 5 in PHP?
Difficulty: MediumType: MCQTopic: Operators
The dot operator in PHP is used for string concatenation, not addition. 10 dot 5 results in '105'.
Correct Answer: 105
Example Code
$result = 10 . 5; // gives 105
9. Which of the following is a PHP superglobal variable?
Difficulty: MediumType: MCQTopic: Superglobals
PHP superglobals are built-in variables accessible anywhere. Examples include $_POST, $_GET, $_SESSION, $_SERVER, and $GLOBALS.
Correct Answer: $GLOBALS
10. Explain the different ways to open and close PHP tags.
Difficulty: EasyType: SubjectiveTopic: PHP Basics
PHP code usually starts with <?php and ends with ?>. Short tags <? and ?> are also supported if enabled in configuration. The long tag is preferred for portability.
Example Code
<?php echo 'Hello'; ?>
11. Describe the different variable scopes in PHP.
Difficulty: MediumType: SubjectiveTopic: Variable Scope
PHP has four main scopes: local, global, static, and parameter. Local variables exist inside functions. Global variables are declared outside functions and accessed with the global keyword. Static variables keep their value between function calls. Parameters are variables passed to functions.
12. How can you convert a string to an integer in PHP?
Difficulty: MediumType: SubjectiveTopic: Type Casting
You can cast a string to an integer using (int) or the intval() function. Example: intval('25') returns 25. Type casting helps in performing numeric operations safely.
Example Code
$num = (int)'25';
13. What is the difference between echo and print in PHP?
Difficulty: MediumType: SubjectiveTopic: Output Basics
Both are used to output data. Echo can take multiple parameters and is slightly faster. Print can take only one argument and always returns one, so it can be used in expressions.
Example Code
echo 'Hi'; print 'Hello';
14. How does PHP execute code on the server?
Difficulty: HardType: SubjectiveTopic: PHP Basics
PHP is an interpreted language. The server reads PHP files, processes the code through the PHP interpreter, and sends the resulting HTML to the client browser. This means users never see the actual PHP code.
15. Which of the following is the correct syntax of an if statement in PHP?
Difficulty: EasyType: MCQTopic: Control Flow
- if x > 10 {}
- if (x > 10) {}
- if (x > 10): endif;
- Both B and C
PHP supports two syntaxes for if statements. The standard uses braces, and the alternate syntax uses a colon with endif for template files.
Correct Answer: Both B and C
Example Code
if ($x > 10) { echo 'Big'; }
// or
if ($x > 10): echo 'Big'; endif;16. What keyword is used to exit a switch statement in PHP?
Difficulty: EasyType: MCQTopic: Control Flow
The break statement stops execution of the current case in a switch block. Without it, PHP continues to the next case.
Correct Answer: break
Example Code
switch($day){ case 'Mon': echo 'Work'; break; }17. How many parameters does a for loop have in PHP?
Difficulty: EasyType: MCQTopic: Control Flow
- Two
- Three
- Four
- Depends on syntax
A for loop includes three expressions: initialization, condition, and increment or decrement.
Correct Answer: Three
Example Code
for($i=0; $i<5; $i++){ echo $i; }18. Which loop checks the condition before executing the block?
Difficulty: EasyType: MCQTopic: Control Flow
A while loop checks the condition first, then executes the body. A do-while loop executes once before checking.
Correct Answer: while
Example Code
while($x < 5){ echo $x; $x++; }19. What is the key difference between while and do-while loops?
Difficulty: MediumType: MCQTopic: Control Flow
- do-while executes at least once
- while executes at least once
- Both same
- None
In do-while, the body runs once before checking the condition. In while, the condition is checked first.
Correct Answer: do-while executes at least once
Example Code
do { echo $x; $x++; } while ($x < 5);20. Which loop is used to iterate through arrays easily in PHP?
Difficulty: MediumType: MCQTopic: Control Flow
The foreach loop is made for iterating arrays. It can loop through both keys and values easily.
Correct Answer: foreach
Example Code
foreach($arr as $val){ echo $val; }21. Which keyword is used to create a function in PHP?
Difficulty: MediumType: MCQTopic: Functions
- function
- define
- declare
- create
Functions are declared using the keyword function, followed by a name and parentheses.
Correct Answer: function
Example Code
function greet(){ echo 'Hello'; }22. What happens if a PHP function does not have a return statement?
Difficulty: MediumType: MCQTopic: Functions
- It returns zero
- It returns null
- It throws an error
- It returns false
If a function has no return statement, PHP automatically returns null. This is common for functions that only print or modify data.
Correct Answer: It returns null
Example Code
function test(){} $x = test(); // null23. How can you define a default parameter value in PHP?
Difficulty: MediumType: MCQTopic: Functions
- Using default()
- Using assign =
- Using var
- Not possible
You can assign a default value using an equal sign in the parameter list. Example: function add($a=10).
Correct Answer: Using assign =
Example Code
function greet($name='User'){ echo $name; }24. Explain what nested loops are and give an example.
Difficulty: MediumType: SubjectiveTopic: Control Flow
Nested loops are loops inside another loop. The inner loop runs completely for each iteration of the outer loop. They are often used for multidimensional arrays or patterns.
Example Code
for($i=0;$i<3;$i++){ for($j=0;$j<3;$j++){ echo $i.$j; } }25. Explain variable scope inside PHP functions.
Difficulty: MediumType: SubjectiveTopic: Variable Scope
Variables inside a function are local by default. To access global variables inside a function, you use the global keyword or the $GLOBALS array.
Example Code
function show(){ global $x; echo $x; }26. What is recursion in PHP functions? Give an example.
Difficulty: MediumType: SubjectiveTopic: Functions
Recursion means a function calls itself until a condition is met. It is used in problems like factorial or tree traversal. Care must be taken to avoid infinite loops.
Example Code
function fact($n){ if($n==1) return 1; return $n*fact($n-1); }27. What are anonymous functions or closures in PHP?
Difficulty: HardType: SubjectiveTopic: Functions
Anonymous functions are functions without a name. They are used as arguments to other functions or stored in variables. Closures can access variables from their parent scope using the use keyword.
Example Code
$add = function($a,$b){ return $a+$b; }; echo $add(2,3);28. Explain pass by reference in PHP functions.
Difficulty: HardType: SubjectiveTopic: Functions
When a variable is passed by reference, the function gets the original variable, not a copy. Changes inside the function affect the original. Use an ampersand before the parameter name.
Example Code
function addOne(&$num){ $num++; } $x=5; addOne($x);29. Which of the following are types of arrays in PHP?
Difficulty: EasyType: MCQTopic: Array Ops
- Indexed, Associative, Multidimensional
- Linear, Nonlinear, Dynamic
- Sequential, Linked, Nested
- Simple, Complex, Composite
PHP arrays can be indexed using numbers, associative using keys, or multidimensional for nested data.
Correct Answer: Indexed, Associative, Multidimensional
Example Code
$arr = array('a','b'); $map = array('name'=>'John');30. Which of the following can be used to create an array in PHP?
Difficulty: EasyType: MCQTopic: Array Ops
- array()
- []
- new Array()
- Both A and B
Arrays can be created using the array() function or square brackets from PHP 5.4 onward.
Correct Answer: Both A and B
Example Code
$a = array(1,2,3); $b = [1,2,3];
31. Which function merges two or more arrays into one?
Difficulty: MediumType: MCQTopic: Array Ops
- join()
- combine()
- array_merge()
- concat()
array_merge() joins arrays. If keys repeat, later values overwrite earlier ones for string keys.
Correct Answer: array_merge()
Example Code
$result = array_merge($a,$b);
32. Which function returns the number of elements in an array?
Difficulty: EasyType: MCQTopic: Array Ops
- size()
- count()
- length()
- num()
The count() function returns the number of elements in an array or object implementing Countable.
Correct Answer: count()
33. What does the function in_array() do?
Difficulty: MediumType: MCQTopic: Array Ops
- Checks if array is empty
- Checks if a value exists in an array
- Removes duplicates
- Adds new value
in_array() searches for a value in an array and returns true if found, false otherwise.
Correct Answer: Checks if a value exists in an array
Example Code
in_array('apple', $fruits);34. Which two functions convert between arrays and strings?
Difficulty: MediumType: MCQTopic: String Ops
- implode() and explode()
- join() and split()
- merge() and cut()
- parse() and stringify()
implode() joins array elements into a string, and explode() splits a string into an array based on a delimiter.
Correct Answer: implode() and explode()
Example Code
$s = implode(',', $arr); $a = explode(',', $s);35. Which function checks if a key exists in an associative array?
Difficulty: MediumType: MCQTopic: Array Ops
- key_exists()
- array_has_key()
- array_key_exists()
- isset_key()
array_key_exists() checks if a key exists in an array. isset() also works but returns false for null values.
Correct Answer: array_key_exists()
Example Code
array_key_exists('name', $user);36. Which function returns the length of a string in PHP?
Difficulty: EasyType: MCQTopic: String Ops
- strlen()
- length()
- count()
- sizeof()
strlen() returns the number of characters in a string, including spaces.
Correct Answer: strlen()
Example Code
strlen('Hello');37. Which function extracts part of a string?
Difficulty: MediumType: MCQTopic: String Ops
- substring()
- substr()
- slice()
- split()
substr() extracts part of a string from a start position and optional length.
Correct Answer: substr()
Example Code
substr('Hello',1,3); // ell38. What is an associative array in PHP? Give an example.
Difficulty: MediumType: SubjectiveTopic: Array Ops
An associative array uses named keys instead of numeric indexes. It is useful for mapping data like name to value pairs.
Example Code
$user = array('name'=>'John','age'=>25);39. Explain multidimensional arrays in PHP.
Difficulty: MediumType: SubjectiveTopic: Array Ops
A multidimensional array contains one or more arrays inside it. It helps represent complex data like tables. Access elements using multiple indexes.
Example Code
$matrix = [[1,2,3],[4,5,6]]; echo $matrix[1][2];
40. List some commonly used string functions in PHP and their uses.
Difficulty: MediumType: SubjectiveTopic: String Ops
Common string functions include strlen for length, strtolower and strtoupper for case conversion, str_replace for replacement, and strpos for searching a substring.
Example Code
strpos('hello world','world');41. How do you traverse an array in PHP?
Difficulty: MediumType: SubjectiveTopic: Array Ops
You can loop through arrays using foreach or for loops. foreach is best for associative arrays. You can access both key and value easily.
Example Code
foreach($arr as $key=>$val){ echo $key.'='.$val; }42. Explain string interpolation in PHP with examples.
Difficulty: HardType: SubjectiveTopic: String Ops
String interpolation means embedding variables inside double-quoted strings. PHP replaces variables with their values. It doesn't work in single quotes.
Example Code
$name='John'; echo "Hello $name"; // prints Hello John
43. Which of the following is NOT a PHP superglobal variable?
Difficulty: EasyType: MCQTopic: Superglobals
- $_POST
- $_DATA
- $_SERVER
- $_SESSION
PHP has several predefined superglobals like $_GET, $_POST, $_SERVER, $_SESSION, but there is no $_DATA variable.
Correct Answer: $_DATA
44. Which HTTP method sends form data through the URL?
Difficulty: EasyType: MCQTopic: HTTP Methods
The GET method appends form data to the URL, making it visible in the address bar. It is used for non-sensitive data requests.
Correct Answer: GET
45. Which PHP superglobal is used to collect form data sent with the POST method?
Difficulty: EasyType: MCQTopic: HTTP Methods
- $_GET
- $_POST
- $_REQUEST
- $_FORM
The $_POST superglobal is used to collect form data sent using the POST method. It is safer for confidential data.
Correct Answer: $_POST
46. Which superglobal provides information about headers, paths, and script locations?
Difficulty: MediumType: MCQTopic: Superglobals
- $_SERVER
- $_FILES
- $_ENV
- $_SESSION
$_SERVER contains server and execution environment information like REQUEST_METHOD, PHP_SELF, and SERVER_NAME.
Correct Answer: $_SERVER
Example Code
echo $_SERVER['PHP_SELF'];
47. What does the PHP superglobal $_REQUEST contain?
Difficulty: MediumType: MCQTopic: Superglobals
- Only POST data
- Only GET data
- Both GET and POST data
- Only cookies
$_REQUEST collects data from both $_GET and $_POST depending on PHP configuration. It is used for flexible form handling.
Correct Answer: Both GET and POST data
48. Which PHP superglobal is used to handle file uploads?
Difficulty: MediumType: MCQTopic: File Upload
- $_FILES
- $_UPLOAD
- $_REQUEST
- $_DATA
The $_FILES array stores information about uploaded files like name, type, size, and temporary location.
Correct Answer: $_FILES
Example Code
echo $_FILES['myfile']['name'];
49. Which function is used to set a cookie in PHP?
Difficulty: MediumType: MCQTopic: Cookies
- cookie()
- setcookie()
- create_cookie()
- makecookie()
setcookie() is used to send a cookie from the server to the client. Cookies store small data on the user's browser.
Correct Answer: setcookie()
Example Code
setcookie('user','John',time()+3600);50. Which function starts a new session or resumes an existing one?
Difficulty: MediumType: MCQTopic: Sessions
- session_run()
- session_create()
- session_start()
- start_session()
session_start() initializes session tracking in PHP. It must be called before any output is sent.
Correct Answer: session_start()
Example Code
session_start(); $_SESSION['user']='John';
51. How do you delete a cookie in PHP?
Difficulty: MediumType: MCQTopic: Cookies
- setcookie('name','')
- unsetcookie('name')
- delete_cookie('name')
- remove_cookie('name')
To delete a cookie, set it again with an expired time using setcookie. PHP has no delete_cookie() function.
Correct Answer: setcookie('name','')
Example Code
setcookie('user','',time()-3600);52. Differentiate between GET and POST methods in PHP forms.
Difficulty: MediumType: SubjectiveTopic: HTTP Methods
GET sends data through the URL, has length limits, and is visible in the address bar. POST sends data in the request body, making it safer for confidential data like passwords.
53. How can you validate form input data in PHP?
Difficulty: MediumType: SubjectiveTopic: Form Handling
You can validate data using functions like empty(), isset(), filter_var(), and regular expressions. Always sanitize inputs to prevent attacks like SQL injection.
Example Code
if(empty($_POST['name'])) echo 'Name required';
54. How do you end a session in PHP?
Difficulty: MediumType: SubjectiveTopic: Sessions
To end a session, use session_unset() to remove variables and session_destroy() to delete the session file on the server.
Example Code
session_unset(); session_destroy();
55. Explain how to prevent CSRF attacks in PHP forms.
Difficulty: HardType: SubjectiveTopic: CSRF Security
To prevent CSRF, generate a random token, store it in the session, and include it as a hidden form field. Verify the token when the form is submitted. If it doesn’t match, reject the request.
Example Code
// Generate token
$_SESSION['token']=bin2hex(random_bytes(16));
56. What are best practices for securing PHP forms?
Difficulty: HardType: SubjectiveTopic: Form Security
Use POST instead of GET for sensitive data, validate and sanitize inputs, use HTTPS, limit file types on upload, and use tokens to prevent CSRF. Also, escape outputs to prevent XSS.
57. Which keyword is used to define a class in PHP?
Difficulty: EasyType: MCQTopic: OOP Basics
In PHP, the keyword 'class' is used to define a class, and 'new' is used to create an object from that class.
Example:
class Car { public $name; }
$car = new Car();
Correct Answer: class
Example Code
class Car { public $brand; }
$car = new Car();58. What is the name of the function automatically called when an object is created?
Difficulty: EasyType: MCQTopic: OOP Basics
- _create()
- __construct()
- __start()
- init()
The __construct() method is called automatically when a class object is created. It is used to initialize values.
Example:
class Car { function __construct(){ echo 'Car ready'; } }
Correct Answer: __construct()
Example Code
class Car {
function __construct(){ echo 'Object created'; }
}59. Which of the following are valid access modifiers in PHP?
Difficulty: MediumType: MCQTopic: OOP Basics
- private, protected, public
- global, static, final
- private, shared, global
- local, global, common
Access modifiers control visibility. Public means accessible everywhere. Protected means within the class and subclasses. Private means only inside the same class.
Correct Answer: private, protected, public
Example Code
class Test { public $a; protected $b; private $c; }60. Which keyword is used for inheritance in PHP?
Difficulty: MediumType: MCQTopic: OOP Basics
- inherits
- extends
- implements
- derives
In PHP, the 'extends' keyword allows one class to inherit properties and methods from another class.
Example:
class ParentClass {}
class ChildClass extends ParentClass {}
Correct Answer: extends
Example Code
class Vehicle {}
class Car extends Vehicle {}61. What is method overriding in PHP?
Difficulty: MediumType: MCQTopic: OOP Basics
- Defining same method in parent and child with different parameters
- Redefining a parent class method in a child class
- Using methods of multiple classes
- None of these
Method overriding means redefining a parent class method inside a child class with the same name and parameters. The child version replaces the parent one when called from the child object.
Correct Answer: Redefining a parent class method in a child class
Example Code
class ParentClass { function greet(){ echo 'Hi'; } }
class Child extends ParentClass { function greet(){ echo 'Hello'; } }62. Which keyword allows accessing class methods or properties without creating an object?
Difficulty: MediumType: MCQTopic: OOP Basics
Static properties and methods belong to the class itself, not to instances. You can access them using ClassName::method().
Correct Answer: static
Example Code
class Math { static $pi=3.14; static function add($a,$b){ return $a+$b; } }
echo Math::$pi;63. What does the keyword $this refer to inside a class method?
Difficulty: MediumType: MCQTopic: OOP Basics
- The class name
- The parent class
- The current object
- A static method
$this refers to the current object instance inside a class. It is used to access class properties or methods of that object.
Correct Answer: The current object
Example Code
class User { public $name; function say(){ echo $this->name; } }64. Which keyword is used to define an interface in PHP?
Difficulty: MediumType: MCQTopic: OOP Basics
- abstract
- interface
- protocol
- implements
An interface defines a set of methods that must be implemented by any class using it. It helps in achieving multiple inheritance in PHP.
Correct Answer: interface
Example Code
interface Animal { public function sound(); }
class Dog implements Animal { public function sound(){ echo 'Bark'; } }65. What is a trait in PHP used for?
Difficulty: MediumType: MCQTopic: OOP Basics
- Multiple inheritance
- Memory optimization
- Encapsulation
- Abstract class creation
Traits allow code reusability in multiple classes. They provide a way to use common methods across unrelated classes.
Correct Answer: Multiple inheritance
Example Code
trait Logger { function log(){ echo 'Logging...'; } }
class App { use Logger; }66. What is an abstract class in PHP? Give an example.
Difficulty: MediumType: SubjectiveTopic: OOP Basics
An abstract class cannot be instantiated directly. It can contain abstract methods that must be defined by child classes. Abstract classes are useful when creating a base class for related objects.
Example:
abstract class Animal { abstract function sound(); }
class Dog extends Animal { function sound(){ echo 'Bark'; } }
Example Code
abstract class Shape { abstract function area(); }67. Explain polymorphism in PHP with example.
Difficulty: MediumType: SubjectiveTopic: OOP Basics
Polymorphism means one interface, many implementations. In PHP, it allows different classes to define methods with the same name but different behaviors. It improves code flexibility.
Example:
interface Shape { public function draw(); }
class Circle implements Shape { function draw(){ echo 'Drawing Circle'; } }
class Square implements Shape { function draw(){ echo 'Drawing Square'; } }
Example Code
interface Shape { function draw(); }68. Differentiate between constructor and destructor in PHP.
Difficulty: MediumType: SubjectiveTopic: OOP Basics
A constructor (__construct) runs automatically when an object is created, often to initialize values. A destructor (__destruct) runs when an object is destroyed or the script ends, used for cleanup like closing database connections.
Example:
class FileHandler {
function __construct(){ echo 'Opening file'; }
function __destruct(){ echo 'Closing file'; }
}
Example Code
class Demo { function __construct(){} function __destruct(){} }69. Explain encapsulation with a simple example in PHP.
Difficulty: MediumType: SubjectiveTopic: OOP Basics
Encapsulation means binding data and methods together while restricting direct access to some data. It is achieved using private and protected access modifiers. This helps maintain control over how data is accessed or changed.
Example:
class BankAccount {
private $balance = 0;
public function deposit($amount){ $this->balance += $amount; }
public function getBalance(){ return $this->balance; }
}
Example Code
class BankAccount { private $balance; }70. Explain object cloning in PHP with example.
Difficulty: HardType: SubjectiveTopic: OOP Advanced
Cloning creates a new object with the same properties as another object. PHP provides the clone keyword for this. You can also define a __clone() method to modify behavior after cloning.
Example:
class User { public $name; }
$u1 = new User(); $u1->name = 'John';
$u2 = clone $u1; $u2->name = 'Sam';
Now $u1 and $u2 are separate objects.
Example Code
$obj2 = clone $obj1;
71. What is late static binding in PHP and why is it used?
Difficulty: HardType: SubjectiveTopic: OOP Advanced
Late static binding allows a child class to reference static methods or properties defined in the parent class using the static keyword instead of self. It ensures that methods refer to the class where they are actually called, not where they are defined.
Example:
class A { static function who(){ echo __CLASS__; } static function test(){ static::who(); } }
class B extends A { static function who(){ echo __CLASS__; } }
B::test(); // Outputs B
Example Code
class Base { static function who(){} static function call(){ static::who(); } }72. Which of the following is NOT a PHP error type?
Difficulty: EasyType: MCQTopic: Error Handling
- Parse Error
- Fatal Error
- Syntax Error
- Null Error
PHP has several error types such as Parse Error, Notice, Warning, and Fatal Error. 'Null Error' is not a real PHP error type.
Correct Answer: Null Error
73. Which function is used to control which PHP errors are reported?
Difficulty: EasyType: MCQTopic: Error Handling
- set_error()
- error_reporting()
- ini_set()
- log_errors()
The error_reporting() function sets which levels of errors PHP reports. For example, error_reporting(E_ALL) enables all errors.
Correct Answer: error_reporting()
Example Code
error_reporting(E_ALL);
74. What block is used to handle exceptions in PHP?
Difficulty: MediumType: MCQTopic: Error Handling
- if-else
- try-catch
- switch
- error-handler
PHP handles exceptions using try-catch blocks. Code that might fail goes in try, and the catch block handles the thrown exception.
Correct Answer: try-catch
Example Code
try { throw new Exception('Error'); } catch(Exception $e) { echo $e->getMessage(); }75. Which keyword is used to throw an exception in PHP?
Difficulty: MediumType: MCQTopic: Error Handling
The throw keyword is used to manually generate an exception in PHP. It is followed by an Exception object.
Correct Answer: throw
Example Code
throw new Exception('Invalid input');76. What is the base class for all exceptions in PHP?
Difficulty: MediumType: MCQTopic: Error Handling
- Error
- Throwable
- Exception
- RuntimeError
The Exception class is the base for all exceptions. You can create your own exceptions by extending it.
Correct Answer: Exception
Example Code
class MyError extends Exception {}77. What is the purpose of the finally block in PHP exceptions?
Difficulty: MediumType: MCQTopic: Error Handling
- To throw a new error
- To execute cleanup code always
- To stop the script
- To rethrow the exception
The finally block always runs after try-catch, even if an exception is thrown. It's often used to close files or database connections.
Correct Answer: To execute cleanup code always
Example Code
try { } catch(Exception $e){ } finally { echo 'Done'; }78. How do you create a custom exception in PHP?
Difficulty: MediumType: MCQTopic: Error Handling
- Extend the Exception class
- Use error_log()
- Override throw()
- Use die()
Custom exceptions are created by extending PHP’s built-in Exception class and overriding its methods if needed.
Correct Answer: Extend the Exception class
Example Code
class MyException extends Exception { }79. Which PHP function writes a message to the server's error log?
Difficulty: MediumType: MCQTopic: Error Handling
- log_error()
- write_log()
- error_log()
- trigger_error()
The error_log() function sends error messages to a log file or email for debugging without displaying them to users.
Correct Answer: error_log()
Example Code
error_log('Database connection failed');80. Which function is used to trigger a user-defined error?
Difficulty: MediumType: MCQTopic: Error Handling
- raise_error()
- trigger_error()
- user_error()
- set_error()
trigger_error() allows you to create custom warning or notice messages in PHP code. Useful for debugging or enforcing logic.
Correct Answer: trigger_error()
Example Code
trigger_error('Invalid input', E_USER_WARNING);81. How can you define a custom error handler function in PHP?
Difficulty: MediumType: SubjectiveTopic: Error Handling
You can define a custom function that handles errors and register it using set_error_handler(). This allows you to manage errors in your own way, such as logging or displaying user-friendly messages.
Example:
function myErrorHandler($errno, $errstr){ echo 'Error: '.$errstr; }
set_error_handler('myErrorHandler');
Example Code
set_error_handler('handlerFunction');82. Explain the exception hierarchy in PHP.
Difficulty: MediumType: SubjectiveTopic: Error Handling
All exceptions in PHP inherit from the Throwable interface. Throwable has two main classes: Error and Exception. The Exception class is for traditional exceptions, while Error represents fatal issues like memory or syntax problems.
83. Show how to create and use a custom exception class in PHP.
Difficulty: MediumType: SubjectiveTopic: Error Handling
You can extend the Exception class to make your own. Inside the catch block, you can handle it differently.
Example:
class InvalidAgeException extends Exception {}
function checkAge($age){ if($age<18) throw new InvalidAgeException('Too young'); }
try{ checkAge(15); } catch(InvalidAgeException $e){ echo $e->getMessage(); }
Example Code
class MyException extends Exception {}84. How can you retrieve details about an exception in PHP?
Difficulty: MediumType: SubjectiveTopic: Error Handling
An Exception object provides methods like getMessage(), getCode(), getFile(), and getLine(). They help identify the reason and location of an error.
Example:
try { throw new Exception('Missing file'); }
catch (Exception $e) {
echo $e->getMessage();
echo $e->getFile();
}
Example Code
$e->getMessage(); $e->getFile();
85. What are best practices for error handling in PHP applications?
Difficulty: HardType: SubjectiveTopic: Error Handling
Best practices include:
1. Using try-catch for predictable errors.
2. Logging errors using error_log().
3. Displaying friendly error pages for users.
4. Keeping display_errors off in production.
5. Validating input to prevent runtime issues.
6. Using custom exceptions for modular handling.
This ensures both developer clarity and user safety.
86. Differentiate between fatal errors and exceptions in PHP.
Difficulty: HardType: SubjectiveTopic: Error Handling
Fatal errors stop script execution immediately, like calling undefined functions. Exceptions, however, can be caught and handled with try-catch blocks.
Example:
Fatal: echo undefinedFunction();
Exception: throw new Exception('Handled safely');
87. Which function is used to open a file in PHP?
Difficulty: EasyType: MCQTopic: File IO
- file_open()
- fopen()
- open_file()
- create_file()
The fopen function opens a file in the specified mode such as read, write, or append. It returns a file handle used for further operations.
Correct Answer: fopen()
Example Code
fopen('data.txt','r');88. What does the mode 'a' mean in fopen?
Difficulty: MediumType: MCQTopic: File IO
- Append and read
- Append only
- Write new file
- Read only
Using mode 'a' opens the file for writing at the end. The pointer moves to the end and preserves existing content.
Correct Answer: Append only
Example Code
fopen('log.txt','a');89. Which function reads a line from an open file?
Difficulty: EasyType: MCQTopic: File IO
- fgets()
- readline()
- read()
- file_get()
The fgets function reads a single line from an open file until it reaches a newline or end of file.
Correct Answer: fgets()
Example Code
$line = fgets($handle);
90. Which function writes data into a file in PHP?
Difficulty: EasyType: MCQTopic: File IO
- fwrite()
- write()
- file_put()
- fstore()
The fwrite function is used to write data to an open file. If the file is not writable, it returns false.
Correct Answer: fwrite()
Example Code
fwrite($handle,'Hello');
91. Which function closes an open file?
Difficulty: EasyType: MCQTopic: File IO
- file_close()
- fclose()
- stop_file()
- end_file()
The fclose function closes an open file handle and frees the system resources associated with it.
Correct Answer: fclose()
Example Code
fclose($handle);
92. Which function reads the entire file into a string?
Difficulty: MediumType: MCQTopic: File IO
- readfile()
- fread()
- file_get_contents()
- get_file()
file_get_contents reads the entire file content into a single string, making it a simple way to load small files.
Correct Answer: file_get_contents()
Example Code
$data = file_get_contents('info.txt');93. Which function writes data directly to a file without opening it manually?
Difficulty: MediumType: MCQTopic: File IO
- fwrite()
- write_file()
- file_put_contents()
- save_file()
file_put_contents writes data to a file in one call. If the file does not exist, it creates it automatically.
Correct Answer: file_put_contents()
Example Code
file_put_contents('info.txt','Hello World');94. How can you check if a file exists before reading it?
Difficulty: MediumType: MCQTopic: File IO
- is_exist()
- file_exists()
- exists_file()
- check_file()
The file_exists function checks if a given path refers to an existing file or directory and returns true or false.
Correct Answer: file_exists()
Example Code
if(file_exists('data.txt')) { echo 'Found'; }95. Which PHP function is used to delete a file?
Difficulty: MediumType: MCQTopic: File IO
- remove()
- delete()
- unlink()
- destroy()
The unlink function deletes a file from the file system. It returns true on success or false on failure.
Correct Answer: unlink()
Example Code
unlink('old.txt');96. Explain the concept of file pointer in PHP file handling.
Difficulty: MediumType: SubjectiveTopic: File IO
A file pointer represents the current position in an open file. Each read or write operation moves the pointer forward. You can manually reposition it using functions like fseek and rewind.
Example Code
fseek($handle,0);
97. Differentiate between fread and file_get_contents.
Difficulty: MediumType: SubjectiveTopic: File IO
fread requires a file handle and reads data in chunks, while file_get_contents reads the entire file directly. fread is suitable for large files or streaming, whereas file_get_contents is best for small files.
Example Code
fread($handle, filesize('data.txt'));98. How do you handle file uploads in PHP?
Difficulty: MediumType: SubjectiveTopic: File Upload
PHP stores uploaded files in a temporary directory using the $_FILES array. You can then move them to a permanent location using move_uploaded_file. Always validate the file type and size for security.
Example Code
move_uploaded_file($_FILES['photo']['tmp_name'],'uploads/photo.jpg');
99. What functions are used to handle directories in PHP?
Difficulty: MediumType: SubjectiveTopic: File IO
PHP provides mkdir to create a directory, rmdir to remove one, and opendir, readdir, closedir to loop through files inside a folder. scandir can also list all files quickly.
Example Code
mkdir('uploads');100. Explain security measures for file uploads in PHP.
Difficulty: HardType: SubjectiveTopic: Upload Security
Always check the MIME type and extension, limit maximum file size, rename uploaded files, and store them outside the web root. Never trust the file name sent by the user to avoid code injection.
101. How do you handle errors when working with files in PHP?
Difficulty: HardType: SubjectiveTopic: Error Handling
Always check return values from functions like fopen, fread, and fwrite. Use file_exists before accessing, and handle failures gracefully using try-catch with file operations or proper conditional checks.
102. Which PHP extension is commonly used to connect to a MySQL database?
Difficulty: EasyType: MCQTopic: DB Connect
- MySQLi
- OracleDB
- MongoDB
- SQLite
MySQLi stands for MySQL Improved. It allows PHP scripts to connect and interact with MySQL databases securely and efficiently.
Correct Answer: MySQLi
Example Code
$conn = mysqli_connect('localhost','root','pass','test');103. What does PDO stand for in PHP?
Difficulty: EasyType: MCQTopic: PDO Basics
- PHP Data Object
- Program Database Operator
- Primary Data Option
- Public Database Object
PDO stands for PHP Data Object. It provides a database abstraction layer that works with many database systems like MySQL, SQLite, and PostgreSQL.
Correct Answer: PHP Data Object
Example Code
$pdo = new PDO('mysql:host=localhost;dbname=test','root','pass');104. What happens if mysqli_connect fails to connect?
Difficulty: EasyType: MCQTopic: DB Connect
- Returns false
- Throws an exception
- Stops script automatically
- Returns true
If mysqli_connect fails, it returns false. You can check this and display an error using mysqli_connect_error.
Correct Answer: Returns false
Example Code
if(!$conn){ echo mysqli_connect_error(); }105. Which function executes an SQL query in MySQLi?
Difficulty: MediumType: MCQTopic: DB Queries
- mysqli_query()
- mysql_execute()
- run_query()
- db_query()
The mysqli_query function sends a query to the MySQL server and returns a result object for SELECT or true for successful INSERT, UPDATE, or DELETE operations.
Correct Answer: mysqli_query()
Example Code
$result = mysqli_query($conn,'SELECT * FROM users');
106. Which MySQLi function fetches a single row from the result set as an associative array?
Difficulty: MediumType: MCQTopic: DB Queries
- mysqli_fetch_assoc()
- mysqli_fetch_row()
- mysqli_fetch_array()
- mysqli_fetch_all()
mysqli_fetch_assoc fetches one row from the result set and returns it as an associative array where column names are used as keys.
Correct Answer: mysqli_fetch_assoc()
Example Code
$row = mysqli_fetch_assoc($result);
107. Why are prepared statements used in PHP?
Difficulty: MediumType: MCQTopic: Prepared Statements
- To improve performance
- To prevent SQL injection
- To simplify code
- Both A and B
Prepared statements increase performance by precompiling SQL and prevent SQL injection by separating query structure from user data.
Correct Answer: Both A and B
Example Code
$stmt = $pdo->prepare('SELECT * FROM users WHERE id=?');108. Which function binds variables to a prepared MySQLi statement?
Difficulty: MediumType: MCQTopic: Prepared Statements
- bindParam()
- mysqli_bind()
- bindVariable()
- bind_param()
The bind_param function binds PHP variables to the SQL query placeholders before execution. It helps ensure secure and structured queries.
Correct Answer: bind_param()
Example Code
$stmt->bind_param('s',$name);109. Which method retrieves rows from a PDO statement as an associative array?
Difficulty: MediumType: MCQTopic: PDO Queries
- fetch()
- get()
- query()
- retrieve()
The fetch method of PDOStatement retrieves the next row from the result set. It can return associative or numeric arrays depending on fetch mode.
Correct Answer: fetch()
Example Code
$row = $stmt->fetch(PDO::FETCH_ASSOC);
110. What is SQL injection and how can it be prevented in PHP?
Difficulty: MediumType: SubjectiveTopic: SQL Injection
SQL injection occurs when untrusted input is directly used in SQL queries, allowing attackers to manipulate database commands. It can be prevented using prepared statements, parameter binding, and input validation before executing queries.
111. Compare MySQLi and PDO in PHP.
Difficulty: MediumType: SubjectiveTopic: DB Drivers
MySQLi works only with MySQL, while PDO supports multiple databases like SQLite and PostgreSQL. PDO provides a consistent API and supports named parameters, while MySQLi offers both object-oriented and procedural styles.
112. How do you handle database connection errors in PHP?
Difficulty: MediumType: SubjectiveTopic: Error Handling
You can check connection results and display user-friendly messages instead of system errors. For PDO, you can enable exceptions using error mode attributes to handle errors cleanly without exposing sensitive information.
113. What is a database transaction and how is it used in PHP?
Difficulty: MediumType: SubjectiveTopic: DB Transactions
A transaction is a sequence of SQL operations that execute as a single unit. It ensures data integrity. You can start a transaction, execute multiple queries, and either commit or roll back if something fails.
Example Code
$pdo->beginTransaction(); $pdo->commit();
114. Explain how PDO handles exceptions and errors.
Difficulty: MediumType: SubjectiveTopic: PDO Basics
PDO can throw exceptions on errors when error mode is set to ERRMODE_EXCEPTION. This allows structured error handling through try-catch blocks instead of checking return values manually.
115. Describe the basic CRUD operations in PHP using a database.
Difficulty: HardType: SubjectiveTopic: CRUD Ops
CRUD stands for Create, Read, Update, and Delete. Create inserts new records, Read retrieves them, Update modifies existing ones, and Delete removes them. All four are performed using SQL queries with secure data handling practices.
116. What are the best practices for managing database connections in PHP?
Difficulty: HardType: SubjectiveTopic: DB Connect
Use environment variables for credentials, close unused connections, use persistent connections only when needed, and always use prepared statements. Avoid hardcoding passwords or connection details directly in scripts.
117. Which function is used to start a session in PHP?
Difficulty: EasyType: MCQTopic: Sessions
- start_session()
- session_start()
- begin_session()
- init_session()
The session_start function initializes or resumes a session. It must be called before any output is sent to the browser to enable PHP to use session variables.
Correct Answer: session_start()
Example Code
session_start();
118. Which superglobal is used to access session variables?
Difficulty: EasyType: MCQTopic: Sessions
- $_SERVER
- $_COOKIE
- $_SESSION
- $_REQUEST
The $_SESSION superglobal holds data for the current session, allowing values to be shared across different pages for the same user.
Correct Answer: $_SESSION
Example Code
$_SESSION['user'] = 'John';
119. Which superglobal retrieves cookie data in PHP?
Difficulty: EasyType: MCQTopic: Cookies
- $_COOKIE
- $_SESSION
- $_POST
- $_ENV
The $_COOKIE superglobal is used to access cookie values that have been sent from the browser back to the server.
Correct Answer: $_COOKIE
Example Code
echo $_COOKIE['user'];
120. Which function is used to destroy a session completely?
Difficulty: MediumType: MCQTopic: Sessions
- session_delete()
- session_reset()
- session_destroy()
- end_session()
The session_destroy function removes all session data stored on the server. It is often used during logout to clear the user’s session.
Correct Answer: session_destroy()
Example Code
session_destroy();
121. Where are PHP session files usually stored by default?
Difficulty: MediumType: MCQTopic: Sessions
- In the database
- In memory
- In temporary files on server
- In browser cache
By default, PHP stores session data as temporary files on the server in a directory defined by the session.save_path configuration in php.ini.
Correct Answer: In temporary files on server
122. What happens if a cookie’s expiration time is set to a past time?
Difficulty: MediumType: MCQTopic: Cookies
- It becomes permanent
- It deletes immediately
- It throws an error
- It ignores the expiry
When a cookie is set with an expiry time in the past, the browser automatically removes it from storage, effectively deleting it.
Correct Answer: It deletes immediately
Example Code
setcookie('user','',time()-3600);123. Which of the following is the main purpose of authentication?
Difficulty: MediumType: MCQTopic: Auth Basics
- Encrypt data
- Verify user identity
- Speed up the site
- Store cookies
Authentication verifies the identity of a user, ensuring that the person logging in is who they claim to be before granting access to protected areas.
Correct Answer: Verify user identity
124. Differentiate between sessions and cookies in PHP.
Difficulty: MediumType: SubjectiveTopic: Sessions Cookies
Cookies store data on the client-side, while sessions store data on the server-side. Cookies persist even after the browser is closed unless expired, whereas sessions usually end when the browser closes. Sessions are safer because data is not directly accessible to users.
125. How does the 'Remember Me' feature work in authentication systems?
Difficulty: MediumType: SubjectiveTopic: Auth Basics
The 'Remember Me' feature stores a long-lived token in a secure cookie when a user logs in. On subsequent visits, the token is validated with the database to auto-login the user. It should always use encrypted tokens to prevent hijacking.
126. How can you make PHP sessions more secure?
Difficulty: MediumType: SubjectiveTopic: Session Security
To secure sessions, use HTTPS to encrypt cookies, regenerate session IDs after login to prevent fixation, set session cookies with HttpOnly and Secure flags, and store minimal sensitive data in sessions.
127. Explain important attributes of cookies.
Difficulty: MediumType: SubjectiveTopic: Cookies
Cookies have attributes like name, value, expiry time, path, domain, and flags such as Secure and HttpOnly. The Secure flag ensures cookies are sent only over HTTPS, and HttpOnly prevents access from JavaScript for safety.
128. Describe a simple user login flow using PHP sessions.
Difficulty: MediumType: SubjectiveTopic: Auth Basics
When a user submits credentials, the system validates them against stored data. If valid, a new session is created with user details. On subsequent pages, PHP checks the session to maintain authentication until logout or session expiry.
129. How can you protect login forms from CSRF attacks in PHP?
Difficulty: HardType: SubjectiveTopic: CSRF Security
You can prevent CSRF by generating a unique token stored in the session and embedding it in each login form. When the form is submitted, the server verifies that the token matches the one stored, ensuring the request is genuine.
130. What steps should be taken during user logout in PHP?
Difficulty: HardType: SubjectiveTopic: Auth Basics
During logout, destroy all session data using session_unset and session_destroy, remove authentication cookies if any, and redirect the user to a public page. This ensures that no residual session data can be reused.
131. What does REST stand for in web development?
Difficulty: EasyType: MCQTopic: REST API
- Representational State Transfer
- Remote Execution Syntax Table
- Read Execute Send Transfer
- Request State Transmission
REST is an architectural style for designing APIs that use standard HTTP methods like GET, POST, PUT, and DELETE for communication between client and server.
Correct Answer: Representational State Transfer
132. Which function is used to convert a PHP array into a JSON string?
Difficulty: EasyType: MCQTopic: JSON
- json_to_array()
- json_encode()
- encode_json()
- array_to_json()
The json_encode function converts PHP data structures like arrays or objects into JSON strings, which can be sent over APIs or stored easily.
Correct Answer: json_encode()
Example Code
json_encode($data);
133. What does the json_decode function do in PHP?
Difficulty: EasyType: MCQTopic: JSON
- Encodes an array
- Decodes a JSON string
- Parses XML
- Creates a database query
The json_decode function converts a JSON string into a PHP array or object, making it easy to handle data from APIs or web services.
Correct Answer: Decodes a JSON string
Example Code
$arr = json_decode($json, true);
134. Which HTTP method is typically used to update existing data on a server?
Difficulty: MediumType: MCQTopic: HTTP Methods
The PUT method is used to update or replace an existing resource on the server. It is idempotent, meaning multiple identical requests produce the same result.
Correct Answer: PUT
135. Which HTTP status code means 'Not Found'?
Difficulty: MediumType: MCQTopic: HTTP Basics
A 404 status code indicates that the server cannot find the requested resource. It’s one of the most common response codes on the web.
Correct Answer: 404
136. What is cURL primarily used for in PHP?
Difficulty: MediumType: MCQTopic: cURL
- File compression
- Making HTTP requests
- Database queries
- Encrypting data
cURL is a PHP library used to send and receive HTTP requests. It helps in communicating with APIs, external services, and web servers programmatically.
Correct Answer: Making HTTP requests
Example Code
$ch = curl_init('https://api.example.com');137. What does the PHP header() function do?
Difficulty: MediumType: MCQTopic: HTTP Basics
- Sends a new HTTP header to the browser
- Modifies cookies
- Creates a new file
- Sets session values
The header function sends raw HTTP headers to the browser before any output. It’s commonly used for redirection and setting content type.
Correct Answer: Sends a new HTTP header to the browser
Example Code
header('Location: login.php');138. Which header specifies the type of content being sent to the browser?
Difficulty: MediumType: MCQTopic: HTTP Basics
- Content-Type
- Accept
- Cache-Control
- Encoding-Type
The Content-Type header tells the browser how to interpret the response data, such as text/html or application/json.
Correct Answer: Content-Type
Example Code
header('Content-Type: application/json');139. Explain the structure of a typical REST API response.
Difficulty: MediumType: SubjectiveTopic: API Basics
A REST API response usually includes a status code, headers, and a body. The body often contains data in JSON format along with success or error messages. Headers describe content type and caching rules.
140. Describe how a PHP script can act as a REST API endpoint.
Difficulty: MediumType: SubjectiveTopic: API Basics
A PHP script reads the HTTP method (GET, POST, etc.), processes input data, performs logic like database operations, and returns a response with proper headers and status codes to the client.
141. Why is JSON preferred over XML in modern web APIs?
Difficulty: MediumType: SubjectiveTopic: JSON
JSON is lightweight, easier to read, and integrates naturally with JavaScript. It requires less bandwidth and simpler parsing compared to XML, making it ideal for fast web communication.
142. What are the main principles of RESTful web services?
Difficulty: MediumType: SubjectiveTopic: REST API
REST is based on stateless communication, resource-based URLs, standard HTTP methods, representation through JSON or XML, and the use of standard status codes for responses.
143. What are the advantages of using cURL in PHP?
Difficulty: MediumType: SubjectiveTopic: cURL
cURL supports multiple protocols, handles headers and cookies, and allows sending data in different formats like JSON or form-data. It is flexible for interacting with REST APIs or external web services securely.
144. How can HTTP headers be used to improve web application security?
Difficulty: HardType: SubjectiveTopic: HTTP Security
Headers like X-Frame-Options, Content-Security-Policy, and X-Content-Type-Options protect against attacks such as clickjacking, cross-site scripting, and MIME sniffing. Setting them correctly hardens PHP web apps against common exploits.
145. Explain how token-based authentication works in PHP APIs.
Difficulty: HardType: SubjectiveTopic: API Security
Token-based authentication verifies users using a unique token generated after login. The token is sent with each API request, and the server validates it before allowing access, eliminating the need to store credentials in every request.
146. What is the purpose of namespaces in PHP?
Difficulty: EasyType: MCQTopic: Namespaces
- Improve performance
- Avoid name conflicts
- Encrypt code
- Handle sessions
Namespaces help organize code and prevent conflicts between classes or functions with the same name. They are especially useful in large applications and libraries.
Correct Answer: Avoid name conflicts
Example Code
namespace MyApp\Controllers;
147. Which PHP feature automatically loads classes when they are needed?
Difficulty: EasyType: MCQTopic: Autoloading
- include
- autoloading
- require_once
- register_class()
Autoloading allows PHP to automatically include the required class file when an object is created. It removes the need for manual include statements.
Correct Answer: autoloading
Example Code
spl_autoload_register(function($class){ include $class.'.php'; });148. What is Composer in PHP?
Difficulty: MediumType: MCQTopic: Composer
- A debugging tool
- A dependency manager
- A web server
- A templating engine
Composer is PHP’s dependency manager. It automatically downloads and installs external libraries and manages their versions for your project.
Correct Answer: A dependency manager
Example Code
composer install
149. What is the purpose of OPCache in PHP?
Difficulty: MediumType: MCQTopic: PHP Performance
- Encrypt code
- Store compiled scripts in memory
- Debug scripts
- Compress output
OPCache improves performance by storing precompiled PHP bytecode in memory, reducing the need for PHP to parse and compile scripts on every request.
Correct Answer: Store compiled scripts in memory
150. Which PHP directive sets the maximum memory a script can use?
Difficulty: MediumType: MCQTopic: PHP Performance
- max_size
- memory_limit
- max_memory
- script_memory
The memory_limit directive in php.ini defines the maximum amount of memory a single PHP script can use, preventing memory overflows.
Correct Answer: memory_limit
Example Code
ini_set('memory_limit','256M');151. What does PHP’s garbage collector do?
Difficulty: MediumType: MCQTopic: PHP Performance
- Deletes unused files
- Reclaims memory from unused objects
- Closes database connections
- Clears cookies
PHP’s garbage collector automatically frees memory by removing objects and variables that are no longer referenced, improving efficiency.
Correct Answer: Reclaims memory from unused objects
Example Code
gc_collect_cycles();
152. What is output buffering used for in PHP?
Difficulty: MediumType: MCQTopic: PHP Performance
- Storing logs
- Temporarily holding script output
- Encrypting output
- Debugging code
Output buffering temporarily holds the output before sending it to the browser. It allows manipulation of headers or compression of data before output.
Correct Answer: Temporarily holding script output
Example Code
ob_start(); echo 'Hello'; ob_end_flush();
153. Which of the following tools can be used for PHP performance profiling?
Difficulty: MediumType: MCQTopic: PHP Performance
- Xdebug
- Composer
- OPCache
- cURL
Xdebug is a PHP extension used for debugging and profiling. It helps developers analyze script execution time and memory usage for performance optimization.
Correct Answer: Xdebug
154. Explain the different types of caching available in PHP.
Difficulty: MediumType: SubjectiveTopic: PHP Performance
Caching in PHP includes opcode caching, data caching, and page caching. Opcode caching stores compiled PHP code, data caching saves computed results in memory or files, and page caching stores whole rendered pages to speed up load times.
155. Why are namespaces important in large PHP applications?
Difficulty: MediumType: SubjectiveTopic: Namespaces
Namespaces prevent naming collisions between classes, functions, or constants from different parts of an application or external libraries. They make the codebase modular, organized, and easier to maintain.
156. What is lazy loading in PHP and why is it beneficial?
Difficulty: MediumType: SubjectiveTopic: PHP Performance
Lazy loading delays object creation or resource initialization until it is actually needed. It reduces startup time and memory usage, improving overall performance in large systems.
157. List some best practices for improving PHP performance.
Difficulty: MediumType: SubjectiveTopic: PHP Performance
Use caching like OPCache, minimize database queries, reuse database connections, enable output buffering, avoid unnecessary loops, and use modern PHP versions. Keeping code modular and using Composer dependencies efficiently also boosts performance.
158. Why is the error suppression operator (@) discouraged in production code?
Difficulty: HardType: SubjectiveTopic: Error Handling
The error suppression operator hides warnings and errors, making debugging difficult. It can also degrade performance because PHP must check and handle suppressed errors internally, even though they’re not shown.
159. How can sessions be optimized for large-scale PHP applications?
Difficulty: HardType: SubjectiveTopic: Session Scaling
Instead of file-based sessions, use database or in-memory stores like Redis for faster access. Regenerate session IDs periodically and use distributed session storage for load-balanced servers to maintain consistency.
160. Explain strategies to reduce PHP script memory usage.
Difficulty: HardType: SubjectiveTopic: PHP Performance
Unset large arrays after use, close database connections, use generators instead of arrays for iteration, and process files in chunks. Avoid loading unnecessary libraries or classes to keep memory consumption minimal.
161. What does JIT stand for in PHP 8?
Difficulty: MediumType: MCQTopic: PHP Performance
- Just in Time
- Join Internal Thread
- Java Interface Translator
- Job Initiation Tool
JIT, or Just in Time compilation, improves performance by compiling PHP bytecode into native machine code during execution, reducing interpretation overhead.
Correct Answer: Just in Time
162. Which PHP 8 feature allows specifying multiple possible data types for a parameter?
Difficulty: MediumType: MCQTopic: PHP 8
- Multi-type hinting
- Union types
- Flexible typing
- Mixed values
Union types let you declare that a parameter or return value can accept multiple types, such as int or float. It improves type safety and flexibility.
Correct Answer: Union types
Example Code
function sum(int|float $a, int|float $b){ return $a+$b; }163. Which new control structure in PHP 8 acts as a safer alternative to switch statements?
Difficulty: MediumType: MCQTopic: PHP 8
- if-else
- match
- compare
- evaluate
The match expression compares a value against multiple conditions like switch, but it returns a value, supports strict comparison, and doesn’t require break statements.
Correct Answer: match
Example Code
echo match($status){ 200 => 'OK', 404 => 'Not Found', default => 'Error' };164. What do named arguments in PHP 8 allow you to do?
Difficulty: MediumType: MCQTopic: PHP 8
- Call functions with unordered parameters
- Create default arguments
- Force strict typing
- Skip optional parameters
Named arguments allow passing arguments to functions by name instead of position, improving code readability and allowing flexible argument ordering.
Correct Answer: Call functions with unordered parameters
Example Code
displayUser(age:25, name:'John');
165. What does the nullsafe operator ( ?-> ) do in PHP 8?
Difficulty: MediumType: MCQTopic: PHP 8
- Throws exception on null
- Executes function anyway
- Prevents errors when accessing null objects
- Checks for empty strings
The nullsafe operator prevents runtime errors when accessing methods or properties on null objects by returning null instead of throwing an error.
Correct Answer: Prevents errors when accessing null objects
Example Code
$user?->getProfile()?->getName();
166. Which PHP 8 feature allows declaring and initializing class properties directly in the constructor parameters?
Difficulty: MediumType: MCQTopic: PHP 8
- Auto promotion
- Constructor property promotion
- Inline initialization
- Compact classes
Constructor property promotion simplifies class definitions by allowing properties to be defined and assigned directly in the constructor parameter list.
Correct Answer: Constructor property promotion
Example Code
class User { function __construct(public string $name, private int $age){} }167. What are attributes in PHP 8 used for?
Difficulty: MediumType: MCQTopic: PHP 8
- Adding metadata to code elements
- Handling errors
- Declaring constants
- Improving loops
Attributes allow developers to add structured metadata to classes, methods, or properties. They can be read using reflection for configuration or annotations.
Correct Answer: Adding metadata to code elements
Example Code
#[Route('/home')] class HomeController {}168. What does the 'mixed' type hint represent in PHP 8?
Difficulty: MediumType: MCQTopic: PHP 8
- A numeric value
- Any type of value
- Only arrays
- A nullable variable
The mixed type allows a variable or function to accept any type, including int, float, string, array, object, or null. It’s useful for flexible APIs.
Correct Answer: Any type of value
Example Code
function processData(mixed $data){ return $data; }169. Which new PHP 8 function checks if a string contains another substring?
Difficulty: EasyType: MCQTopic: PHP 8
- strpos()
- str_has()
- str_contains()
- string_includes()
The str_contains function returns true if one string is found within another. It replaces the need for using strpos with manual comparison.
Correct Answer: str_contains()
Example Code
str_contains('Hello World','World');170. What is a WeakMap in PHP 8 used for?
Difficulty: MediumType: MCQTopic: PHP 8
- Mapping weak variables
- Associating data with objects without preventing garbage collection
- Encrypting arrays
- Tracking sessions
A WeakMap stores object references as keys without preventing them from being garbage collected, improving memory efficiency in complex systems.
Correct Answer: Associating data with objects without preventing garbage collection
Example Code
$map = new WeakMap();
171. How does the match expression differ from a switch statement in PHP 8?
Difficulty: MediumType: SubjectiveTopic: PHP 8
Match is an expression that returns a value, uses strict comparison by default, and doesn’t require break statements. It’s more concise and avoids fall-through issues common in switch statements.
172. Explain the use cases of attributes in PHP 8.
Difficulty: MediumType: SubjectiveTopic: PHP 8
Attributes add metadata to code structures. They are commonly used in frameworks for routing, validation, or ORM configuration, replacing PHPDoc comments with structured syntax that can be parsed at runtime.
173. What are the benefits of the nullsafe operator in PHP 8?
Difficulty: MediumType: SubjectiveTopic: PHP 8
It simplifies null checks by allowing chained property or method calls without explicit if statements. If any object in the chain is null, the entire expression safely returns null instead of causing an error.
174. How does JIT compilation improve PHP performance?
Difficulty: MediumType: SubjectiveTopic: PHP Performance
JIT compilation turns frequently executed PHP bytecode into native machine code at runtime. This reduces CPU overhead, leading to faster execution for computation-heavy scripts like data processing or graphics generation.
175. Summarize the key benefits introduced with PHP 8.
Difficulty: HardType: SubjectiveTopic: PHP 8
PHP 8 introduced faster performance with JIT, better type safety using union and mixed types, cleaner syntax through constructor property promotion, and improved developer experience with named arguments and match expressions. It also enhanced error handling and security consistency.
176. What is Laravel primarily used for?
Difficulty: EasyType: MCQTopic: Laravel Basics
- Game development
- Web application development
- Mobile apps
- Desktop software
Laravel is a popular open-source PHP framework designed to simplify web application development using the MVC architecture and elegant syntax.
Correct Answer: Web application development
177. What does MVC stand for in Laravel?
Difficulty: EasyType: MCQTopic: Laravel MVC
- Model View Controller
- Main View Component
- Module Value Configuration
- Model Variable Control
MVC stands for Model View Controller. It separates data handling (Model), presentation (View), and business logic (Controller) for better organization and maintainability.
Correct Answer: Model View Controller
178. What is Artisan in Laravel?
Difficulty: MediumType: MCQTopic: Laravel Artisan
- A routing tool
- A CLI tool
- A database driver
- A templating engine
Artisan is Laravel’s command-line interface. It automates repetitive tasks such as creating controllers, models, and migrations, and running maintenance commands.
Correct Answer: A CLI tool
Example Code
php artisan make:controller UserController
179. In which file are web routes defined in a Laravel application?
Difficulty: MediumType: MCQTopic: Laravel Routing
- routes/api.php
- routes/web.php
- app/routes.php
- config/routes.php
All web routes that respond to HTTP requests in Laravel are typically defined in the routes/web.php file using simple route definitions.
Correct Answer: routes/web.php
Example Code
Route::get('/home', [HomeController::class, 'index']);180. What is Eloquent in Laravel?
Difficulty: MediumType: MCQTopic: Eloquent ORM
- A caching system
- An ORM
- A database migration tool
- A session manager
Eloquent is Laravel’s Object-Relational Mapper that simplifies database interactions by representing tables as models with expressive query methods.
Correct Answer: An ORM
Example Code
User::where('active',1)->get();181. What are migrations in Laravel used for?
Difficulty: MediumType: MCQTopic: DB Migrations
- Managing database schema
- Migrating servers
- Moving routes
- Cloning views
Migrations are version control for your database. They allow you to create, modify, and share database structures across different environments easily.
Correct Answer: Managing database schema
Example Code
php artisan make:migration create_users_table
182. What is Blade in Laravel?
Difficulty: MediumType: MCQTopic: Blade Templates
- A database tool
- A command-line interface
- A templating engine
- A CSS framework
Blade is Laravel’s powerful templating engine that allows embedding PHP code in HTML cleanly using simple syntax. It supports layouts, loops, and conditionals.
Correct Answer: A templating engine
Example Code
@if($user) Welcome, {{ $user->name }} @endif183. What is middleware in Laravel?
Difficulty: MediumType: MCQTopic: Laravel Middleware
- A data model
- A request filter
- A routing system
- A session manager
Middleware filters HTTP requests entering your application. It’s often used for authentication, logging, and modifying requests or responses before reaching controllers.
Correct Answer: A request filter
Example Code
php artisan make:middleware CheckUser
184. What is a Service Provider in Laravel?
Difficulty: MediumType: MCQTopic: Service Providers
- A configuration file
- The central place for app bootstrapping
- A controller helper
- A route manager
Service Providers bootstrap application services like event listeners, middleware, and routes. They register bindings and configurations during app startup.
Correct Answer: The central place for app bootstrapping
185. What are Facades in Laravel?
Difficulty: MediumType: SubjectiveTopic: Laravel Facades
Facades provide a static interface to classes registered in the Laravel service container. They make code cleaner and allow quick access to framework features like Cache, DB, and Route without creating objects manually.
186. What are the advantages of using Artisan commands in Laravel?
Difficulty: MediumType: SubjectiveTopic: Laravel Artisan
Artisan automates repetitive development tasks like creating controllers, models, and migrations. It improves productivity, reduces manual errors, and helps with tasks like database seeding and clearing caches.
187. Explain relationships in Eloquent ORM.
Difficulty: MediumType: SubjectiveTopic: Eloquent ORM
Eloquent supports relationships like one-to-one, one-to-many, and many-to-many. These allow models to access related data through readable methods, simplifying database joins and queries.
188. Why is middleware important in Laravel applications?
Difficulty: MediumType: SubjectiveTopic: Laravel Middleware
Middleware ensures that requests meet specific conditions before processing. It enhances security and efficiency by handling authentication, role checking, and input validation at a centralized layer.
189. List some advantages of using Laravel framework.
Difficulty: MediumType: SubjectiveTopic: Laravel Basics
Laravel offers clean syntax, built-in authentication, robust routing, ORM with Eloquent, easy database migrations, Blade templates, and a large community. It enables rapid and secure web application development.
190. Explain the request lifecycle in Laravel.
Difficulty: HardType: SubjectiveTopic: Request Lifecycle
A request enters Laravel through public/index.php, is handled by middleware, routes to a controller via the router, executes business logic, and returns a response. Service providers and middleware play key roles in preparing the environment.
191. Which PHP function can reverse a string?
Difficulty: EasyType: MCQTopic: Coding Tasks
- reverse()
- strrev()
- array_reverse()
- flip_string()
The strrev function reverses the order of characters in a string and returns the reversed string.
Correct Answer: strrev()
Example Code
echo strrev('Hello'); // olleH192. How can you count the total number of elements in an array?
Difficulty: EasyType: MCQTopic: Array Ops
- length()
- size()
- count()
- sizeofarray()
The count function returns the total number of elements in an array or the number of properties in an object.
Correct Answer: count()
Example Code
count([1,2,3,4]); // 4
193. Which of the following describes a palindrome string?
Difficulty: MediumType: MCQTopic: Coding Tasks
- A string with spaces
- A string that reads the same backward and forward
- A string with uppercase letters
- A string that has digits only
A palindrome string remains the same when reversed, such as level or madam. Checking this is a common PHP coding test question.
Correct Answer: A string that reads the same backward and forward
194. What is the factorial of 5?
Difficulty: MediumType: MCQTopic: Coding Tasks
The factorial of a number is the product of all positive integers up to that number. So 5 factorial equals 5 × 4 × 3 × 2 × 1, which is 120.
Correct Answer: 120
195. What is the next number in the Fibonacci sequence: 0, 1, 1, 2, 3, 5, ?
Difficulty: MediumType: MCQTopic: Coding Tasks
Each number in the Fibonacci sequence is the sum of the two preceding ones. After 5 comes 8 (3 + 5).
Correct Answer: 8
196. Which PHP function sorts an array in ascending order by values?
Difficulty: MediumType: MCQTopic: Array Ops
- asort()
- ksort()
- sort()
- rsort()
The sort function arranges array elements in ascending order by value while reindexing the array numerically.
Correct Answer: sort()
197. Which operator can check if a number is even or odd in PHP?
Difficulty: EasyType: MCQTopic: Coding Tasks
The modulus operator (%) checks the remainder of division. If number % 2 equals zero, the number is even; otherwise, it's odd.
Correct Answer: %
Example Code
if($num % 2 == 0) echo 'Even';
198. Which PHP function returns the sum of all elements in an array?
Difficulty: EasyType: MCQTopic: Array Ops
- sum()
- array_sum()
- total()
- calculate_sum()
The array_sum function adds up all numeric elements of an array and returns the total.
Correct Answer: array_sum()
Example Code
array_sum([2,4,6]); // 12
199. How would you reverse the order of words in a string using PHP?
Difficulty: MediumType: SubjectiveTopic: Coding Tasks
You can split the string into an array of words, reverse the array, and join it back into a string. This rearranges word order rather than individual letters.
Example Code
$words = explode(' ', $str); echo implode(' ', array_reverse($words));200. How can you remove duplicate values from an array in PHP?
Difficulty: MediumType: SubjectiveTopic: Coding Tasks
You can use array_unique to remove duplicate entries. It keeps only the first occurrence of each value and returns a new array with unique elements.
Example Code
$unique = array_unique($arr);
201. How can you count the number of words in a string?
Difficulty: MediumType: SubjectiveTopic: String Ops
PHP provides str_word_count to count how many words exist in a given string. This is often used for text analysis and content length checks.
Example Code
str_word_count('Hello world!');202. How do you find the largest and smallest number in an array?
Difficulty: MediumType: SubjectiveTopic: Array Ops
You can use the built-in functions max and min to quickly retrieve the highest and lowest values in an array without manually looping through the data.
Example Code
max($arr); min($arr);
203. How can you check if a given string is a palindrome in PHP?
Difficulty: MediumType: SubjectiveTopic: Coding Tasks
A palindrome check can be done by comparing the string with its reversed version. If both are equal, the string is a palindrome.
Example Code
if($str == strrev($str)) echo 'Palindrome';
204. How can you find elements present in one array but not in another?
Difficulty: MediumType: SubjectiveTopic: Array Ops
The array_diff function compares two or more arrays and returns values from the first array that are not present in the others.
Example Code
array_diff($arr1,$arr2);
205. How would you print a pyramid pattern in PHP?
Difficulty: HardType: SubjectiveTopic: Coding Tasks
You can use nested loops. The outer loop controls rows, and the inner loop prints spaces and stars in each row, creating a pyramid shape. This tests logical thinking and loop control understanding.
206. What is the main purpose of escaping output in PHP?
Difficulty: MediumType: MCQTopic: XSS Security
- Prevent SQL errors
- Avoid XSS attacks
- Improve speed
- Hide PHP version
Escaping output ensures user input is shown as plain text instead of executable HTML or JavaScript. This prevents Cross-Site Scripting attacks.
Correct Answer: Avoid XSS attacks
Example Code
echo htmlspecialchars($input, ENT_QUOTES);
207. How can PHP applications protect against CSRF attacks?
Difficulty: MediumType: MCQTopic: CSRF Security
- Use HTTPS only
- Use CSRF tokens
- Store passwords in cookies
- Minimize sessions
A CSRF token is a random, unique value added to each form or request. The server verifies it to ensure the request came from a trusted source, preventing forgery attacks.
Correct Answer: Use CSRF tokens
208. Which of the following is the safest way to prevent SQL injection?
Difficulty: MediumType: MCQTopic: SQL Injection
- Use mysqli_query()
- Escape quotes manually
- Use prepared statements
- Use eval()
Prepared statements separate SQL logic from user input. This prevents attackers from injecting malicious SQL through form inputs or URLs.
Correct Answer: Use prepared statements
Example Code
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');209. Which PHP function should be used to securely store user passwords?
Difficulty: MediumType: MCQTopic: Password Security
- md5()
- sha1()
- password_hash()
- crypt()
The password_hash function automatically salts and hashes passwords using strong algorithms like bcrypt, making stored passwords secure.
Correct Answer: password_hash()
Example Code
password_hash('mypassword', PASSWORD_DEFAULT);210. Which step can reduce the risk of session hijacking?
Difficulty: MediumType: MCQTopic: Session Security
- Store session ID in URL
- Use HTTPS and regenerate session ID
- Disable cookies
- Use GET requests
Using HTTPS encrypts session data in transit, while regenerating session IDs after login prevents attackers from reusing old session tokens.
Correct Answer: Use HTTPS and regenerate session ID
Example Code
session_regenerate_id(true);
211. What is a good practice for error display in production?
Difficulty: MediumType: MCQTopic: Error Handling
- Turn on display_errors
- Echo errors on the screen
- Log errors and hide from users
- Ignore warnings
In production, sensitive error messages should not be visible to users. Instead, errors should be logged securely for developers to review later.
Correct Answer: Log errors and hide from users
Example Code
ini_set('display_errors',0); ini_set('log_errors',1);212. What should typically be excluded from version control when deploying a PHP app?
Difficulty: MediumType: MCQTopic: Deployment
- index.php
- .env file
- composer.json
- routes/web.php
The .env file contains sensitive information like API keys and database credentials. It should never be shared or committed to version control.
Correct Answer: .env file
213. What is the purpose of an API key in web applications?
Difficulty: MediumType: MCQTopic: API Security
- Speed up responses
- Identify and authorize requests
- Encrypt data
- Cache results
API keys are unique identifiers used to authenticate and track client access to an API. They help control usage and prevent unauthorized access.
Correct Answer: Identify and authorize requests
214. What are some methods to optimize PHP code for better performance?
Difficulty: MediumType: SubjectiveTopic: PHP Performance
Use caching mechanisms like OPCache, minimize database queries, reuse database connections, avoid nested loops, and leverage built-in PHP functions instead of manual logic. Using the latest PHP version also improves execution speed.
215. List some common PHP security best practices.
Difficulty: MediumType: SubjectiveTopic: Web Security
Always sanitize user input, escape output, use prepared statements for database queries, hash passwords, disable display_errors in production, validate file uploads, and keep the PHP version updated for latest security patches.
216. Why can file uploads be dangerous, and how can they be secured?
Difficulty: MediumType: SubjectiveTopic: Upload Security
If not validated, malicious files like PHP shells can be uploaded and executed. To secure uploads, restrict file types, limit file sizes, rename files on upload, and store them outside the public web root.
217. How can a PHP web application be scaled to handle heavy traffic?
Difficulty: MediumType: SubjectiveTopic: App Scaling
Use caching for static data, load balancing across multiple servers, database optimization, asynchronous job queues, and CDNs for assets. Stateless design helps distribute load efficiently.
218. Which tools or techniques are useful for debugging PHP applications?
Difficulty: MediumType: SubjectiveTopic: Debugging
Tools like Xdebug and Laravel Telescope help inspect runtime errors, variable states, and queries. Logging with Monolog and using PHP’s built-in error_log also simplify debugging and monitoring in real projects.
219. Describe best practices for deploying a PHP application to production.
Difficulty: HardType: SubjectiveTopic: Deployment
Always use environment variables for secrets, run composer install with optimized autoload, enable caching, compress assets, set correct file permissions, and monitor logs. Use CI/CD pipelines for safe, repeatable deployments.
220. A PHP page works locally but fails on production. How would you troubleshoot it?
Difficulty: HardType: SubjectiveTopic: Debugging
Check PHP version differences, missing extensions, incorrect file permissions, or case-sensitive filenames on Linux. Reviewing logs and environment configuration usually reveals the mismatch causing failure.