1. What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development but also used as a general-purpose programming language.
2. What are the main features of PHP?
- Open-source
- Cross-platform compatibility
- Supports various databases (MySQL, PostgreSQL, MongoDB)
- Object-oriented programming support
- Built-in security functions
- Supports integration with HTML, CSS, JavaScript
3. What is the difference between echo
and print
?
echo
can take multiple parameters and does not return a value.print
can only take one parameter and returns 1, so it can be used in expressions.
Example:
echo "Hello", " World!"; // Works
print "Hello"; // Works
4. What is the difference between ==
and ===
in PHP?
==
checks for value equality, ignoring type.===
checks for both value and type.
Example:
var_dump(5 == "5"); // true
var_dump(5 === "5"); // false
5. How do you declare a PHP variable?
All PHP variables start with a $ sign, followed by the variable name.
$name = "John";
$age = 30;
6. What is the scope of a variable in PHP?
PHP variables have four types of scope:
- Local – Defined within a function
- Global – Defined outside a function
- Static – Retains value between function calls
- Superglobal –
$GLOBALS
,$_POST
,$_GET
, etc.
7. How do you create a constant in PHP?
Use define()
or const
.
define("SITE_NAME", "MyWebsite");
const API_KEY = "123456";
8. What is the difference between require
and include
?
require
throws a fatal error if the file is missing.include
throws a warning but continues execution.
Example:
require "file.php"; // Script stops if not found
include "file.php"; // Script continues even if missing
9. What is the difference between require_once
and require
?
require_once
ensures the file is included only once, preventing multiple inclusions.require
allows multiple inclusions.
10. How can you connect to a MySQL database in PHP?
Using MySQLi (improved) or PDO.
MySQLi Example:
$conn = new mysqli("localhost", "user", "password", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
PDO Example:
try {
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
11. What is the difference between MySQLi and PDO?
- MySQLi is specific to MySQL, whereas PDO supports multiple databases.
- PDO uses prepared statements more efficiently.
12. What is a PHP session?
A session stores user-specific information across multiple pages.
session_start();
$_SESSION["user"] = "John";
13. What is a PHP cookie?
Cookies store small data on the user's computer.
setcookie("username", "John", time() + (86400 * 30), "/");
14. What is the difference between isset()
and empty()
?
isset()
checks if a variable is declared and not null.empty()
checks if a variable is empty (0, "", null, false, array()).
15. What are magic methods in PHP?
Magic methods start with double underscores (__
), like __construct()
, __destruct()
, __get()
, __set()
, etc.
Example:
class Test {
function __construct() {
echo "Object created!";
}
}
$obj = new Test(); // Outputs: Object created!
16. What is the difference between GET
and POST
?
Feature | GET | POST |
---|---|---|
Visibility | Data is visible in the URL | Data is hidden |
Security | Less secure | More secure |
Data Limit | Limited (URL length) | No limit |
Usage | Fetching data | Submitting forms |
17. What are PHP superglobals?
PHP provides predefined variables, such as:
$_GET
$_POST
$_SESSION
$_COOKIE
$_SERVER
$_FILES
18. How to handle errors in PHP?
Using try...catch
.
try {
$num = 5 / 0;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
19. What are PHP data types?
- String
- Integer
- Float
- Boolean
- Array
- Object
- NULL
- Resource
20. How to prevent SQL Injection in PHP?
Use prepared statements.
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
Advanced Questions
21. What is Composer in PHP?
A dependency manager for PHP packages.
22. What is the difference between traits and interfaces?
- Traits allow multiple inheritance.
- Interfaces define required methods.
23. What is spl_autoload_register()
?
Automatically loads class files without require
.
spl_autoload_register(function($class) {
include $class . ".php";
});
24. What are namespaces in PHP?
Avoids name conflicts.
namespace MyNamespace;
class Test {}
25. What are anonymous functions?
Functions without names.
$greet = function($name) { return "Hello, $name"; };
echo $greet("John");
26. What is the difference between an abstract class and an interface?
Feature | Abstract Class | Interface |
---|---|---|
Method Definition | Can have both abstract and concrete methods | Only method signatures (no implementation) |
Variables | Can have properties | Cannot have properties |
Multiple Inheritance | No | Yes (A class can implement multiple interfaces) |
Constructor | Yes | No |
Example:
abstract class Animal {
abstract public function makeSound();
}
interface CanFly {
public function fly();
}
27. What is PSR in PHP?
PSR (PHP Standard Recommendations) defines coding standards for PHP projects.
Examples:
- PSR-1: Basic coding standard
- PSR-2: Coding style guide
- PSR-4: Autoloading standard
28. What is Laravel?
Laravel is a PHP framework for web applications, offering:
- MVC architecture
- Eloquent ORM
- Blade templating
- Authentication & Authorization
- Artisan CLI
29. What are PHP generators?
Generators return values on demand using yield
, saving memory.
function getNumbers() {
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
foreach (getNumbers() as $num) {
echo $num; // 1 2 3
}
30. How to implement caching in PHP?
Using APCu, Redis, or Memcached.
Example with APCu:
apcu_store('key', 'value', 300); // Store for 5 minutes
$value = apcu_fetch('key');
31. How to handle file uploads in PHP?
Use $_FILES
.
if ($_FILES["file"]["error"] == 0) {
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
}
32. What is the difference between REST and SOAP APIs?
Feature | REST | SOAP |
---|---|---|
Protocol | HTTP, JSON | XML-RPC |
Simplicity | Easy | Complex |
Speed | Faster | Slower |
State | Stateless | Stateful |
33. What are the different types of errors in PHP?
- Parse Error – Syntax errors
- Fatal Error – Undefined functions or missing files
- Warning – Non-fatal issues
- Notice – Minor issues
Example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
34. How does PHP manage memory?
PHP uses Garbage Collection (GC) to free unused memory.
For manual cleanup:
gc_collect_cycles();
35. How to prevent Cross-Site Scripting (XSS) in PHP?
Use htmlspecialchars()
:
echo htmlspecialchars("<script>alert('Hacked');</script>");
36. What is the difference between explode()
and implode()
?
explode()
converts a string to an array.implode()
converts an array to a string.
Example:
$arr = explode(",", "apple,banana,grape");
$str = implode("-", $arr);
37. How to use cURL in PHP?
cURL is used for making HTTP requests.
$ch = curl_init("https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
38. What is the difference between foreach
and for
loop?
for
is used with index-based arrays.foreach
is used with associative arrays and objects.
Example:
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color;
}
39. What are type hinting and strict types in PHP?
Type hinting enforces data types in function arguments.
function add(int $a, int $b): int {
return $a + $b;
}
Enable strict types at the beginning of a file:
declare(strict_types=1);
40. How to implement CSRF protection in PHP?
Use CSRF tokens in forms:
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
Validate token before form submission.
41. What is a prepared statement in PHP?
A method to prevent SQL injection.
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
42. What is the difference between array_merge()
and array_combine()
?
array_merge()
joins two arrays.array_combine()
creates an associative array from two arrays.
Example:
$keys = ['name', 'age'];
$values = ['John', 30];
$result = array_combine($keys, $values);
43. How to sort an array in PHP?
sort($arr); // Ascending
rsort($arr); // Descending
asort($arr); // Ascending associative
ksort($arr); // Sort by key
44. What are lambda functions in PHP?
Anonymous functions assigned to variables.
$sum = function($a, $b) { return $a + $b; };
echo $sum(2, 3);
45. What is the difference between json_encode()
and json_decode()
?
json_encode()
converts PHP to JSON.json_decode()
converts JSON to PHP.
Example:
$json = json_encode(["name" => "John"]);
$data = json_decode($json, true);
46. What is a singleton class in PHP?
A class that allows only one instance.
class Singleton {
private static $instance = null;
private function __construct() {}
public static function getInstance() {
if (!self::$instance) self::$instance = new Singleton();
return self::$instance;
}
}
47. What is dependency injection in PHP?
A design pattern for managing dependencies.
class Logger {
public function log($message) { echo $message; }
}
class User {
private $logger;
public function __construct(Logger $logger) { $this->logger = $logger; }
}
48. What is array_map()
in PHP?
Applies a function to all elements of an array.
$numbers = [1, 2, 3];
$squared = array_map(fn($n) => $n * $n, $numbers);
49. How to send an email using PHP?
Using mail()
function:
mail("user@example.com", "Subject", "Message");
Or using PHPMailer for better handling.
50. How to optimize PHP performance?
- Use opcode caching (OPcache)
- Optimize database queries
- Use lazy loading
- Implement CDN & caching
- Avoid unnecessary loops
- Enable compression (Gzip)
Thanks for Visiting if you want more php topics then comment we provide immediately that you want.