Survive The Deep End: PHP Security
Table Of Contents
  1. What is foreach used for in PHP
  2. When should you use pass-by-reference arguments in PHP
  3. What is … used for in PHP
  4. What happens if the variadic operator is placed before another parameter in a PHP function
  5. What does strict mode do in PHP
  6. What are return type declarations in PHP
  7. What are the different types of arrays in PHP
  8. What is the difference between indexed and associative arrays
  9. How do you add and remove elements from an array
  10. What is the difference between array_merge and the + operator
  11. How does PHP handle array copying
  12. What is the difference between in_array and array_search
  13. What is the difference between isset and array_key_exists
  14. What are array_map and array_filter used for
  15. What is the difference between sort and asort
  16. How do you remove duplicate values from an array
  17. What is a common mistake with array_search
  18. How do you loop through an array efficiently
  19. What is the difference between count and sizeof
  20. How do you check if a variable is an array
  21. What is the difference between array_slice and array_splice
  22. What are superglobals in PHP
  23. What are the main PHP superglobals
  24. What is $GLOBALS used for
  25. What is $_SERVER used for
  26. What is the difference between $_GET and $_POST
  27. What is $_REQUEST
  28. What is $_FILES used for
  29. What is $_SESSION used for
  30. What is $_COOKIE used for
  31. What is $_ENV used for
  32. What is a common security issue with superglobals
  33. What is the difference between $GLOBALS and global keyword
  34. How do you secure data coming from $_GET or $_POST
  35. What is a regular expression in PHP
  36. What are the main regex functions in PHP
  37. What does preg_match do
  38. What is the difference between preg_match and preg_match_all
  39. What does preg_replace do
  40. What does preg_split do
  41. What does preg_grep do
  42. What are delimiters in regex
  43. What does the i modifier do
  44. What does ^ and $ mean
  45. What is the difference between . and .*
  46. What is a common mistake in regex
  47. What is the difference between greedy and lazy matching
  48. What is a form in PHP
  49. What is the difference between GET and POST in forms
  50. What is the action attribute in a form
  51. What is the method attribute in a form
  52. How do you access form data in PHP
  53. What is a common security issue with forms
  54. How do you validate form data in PHP
  55. What is the difference between client-side and server-side validation
  56. What is CSRF and how do you prevent it
  57. What is XSS and how do you prevent it
  58. What is enctype in forms
  59. What is the role of $_FILES in forms
  60. What is a common mistake when handling forms
  61. What is the PRG pattern
  62. What are date and time functions in PHP
  63. What does date() function do
  64. What is a timestamp in PHP
  65. What is the difference between date() and DateTime
  66. How do you set timezone in PHP
  67. What does strtotime() do
  68. How do you add or subtract time
  69. What is DateInterval
  70. What is DatePeriod
  71. What is the difference between gmdate and date
  72. What is a common mistake with date and time
  73. What is the difference between include and require in PHP
  74. When should you use include
  75. When should you use require
  76. What are include_once and require_once
  77. What is a common mistake with include and require
  78. What is a file in PHP
  79. How do you open a file in PHP
  80. What are common file modes
  81. How do you read a file
  82. How do you write to a file
  83. How do you close a file
  84. What is file_get_contents
  85. What is file_put_contents
  86. What is a common mistake with file handling
  87. What are cookies and sessions in PHP
  88. What is a cookie
  89. How do you access cookies
  90. What is a session
  91. How do you access session data
  92. What is the difference between cookies and sessions
  93. What is a common security issue with cookies
  94. How do you destroy a session
  95. What is a common mistake with sessions
  96. What is the role of session ID

What is foreach used for in PHP

foreach is used to iterate over arrays and objects. It loops through each element without using an index.

Basic use with values

$nums = [1, 2, 3];

foreach ($nums as $num) {
    echo $num;
}

Use with keys and values

$user = ["name" => "Amr", "age" => 23];

foreach ($user as $key => $value) {
    echo $key . ": " . $value;
}

Modify array values using reference

$nums = [1, 2, 3];

foreach ($nums as &$num) {
    $num *= 2;
}
unset($num);

Use with objects

class User {
    public $name = "Amr";
    public $age = 23;
}

$user = new User();

foreach ($user as $key => $value) {
    echo $key . ": " . $value;
}

Nested arrays

$data = [[1,2], [3,4]];

foreach ($data as $row) {
    foreach ($row as $item) {
        echo $item;
    }
}

Common mistake

$arr = [1, 2, 3];

foreach ($arr as $v) {
    $v += 10;
}

print_r($arr);

Output
[1, 2, 3]

$v is a copy, not a reference

When should you use pass-by-reference arguments in PHP

Use it when the function must modify the original variable

  • The function updates the caller’s data
  • You want side effects by design
function increment(&$x) {
    $x++;
}

$a = 5;
increment($a);
echo $a; // 6

Use it to avoid copying large data

  • Large arrays or structures
  • Tight loops or heavy processing
function normalize(array &$items) {
    foreach ($items as &$v) {
        $v = trim($v);
    }
    unset($v);
}

Use it to return multiple results without arrays

  • Cleaner when outputs are few and known
function stats($a, $b, &$sum, &$diff) {
    $sum = $a + $b;
    $diff = $a - $b;
}

When not to use it

  • Simple values
  • Public APIs where side effects confuse users
  • When immutability improves safety

Key points

  • Default is copy-on-write
  • Reference uses & and shares the same value
  • Changes affect the original variable

Common mistake

  • Forgetting that references persist
foreach ($arr as &$v) {}
unset($v);

What is … used for in PHP

It is the spread and variadic operator

Use case 1 Variadic functions
Accept a variable number of arguments

function sum(...$numbers) {
    return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10

$numbers becomes an array

Use case 2 Argument unpacking
Pass array values as separate arguments

function add($a, $b, $c) {
    return $a + $b + $c;
}
$nums = [1, 2, 3];
echo add(...$nums); // 6

Use case 3 Array spreading
Merge arrays

$a = [1, 2];
$b = [3, 4];
$result = [...$a, ...$b];
print_r($result);

Key idea
In function definition it collects arguments
In function call or array it expands values

Common mistake

add(...[1,2]); // error

Quick check

function test($a, ...$b) {
    return count($b);
}
echo test(1,2,3,4);

3

What happens if the variadic operator is placed before another parameter in a PHP function

It causes a fatal error because the variadic parameter must be the last parameter in the function signature

What does strict mode do in PHP

Strict mode enforces strict type checking in PHP. When enabled using declare(strict_types=1), PHP will not perform type coercion for function arguments or return values. This means values must match the declared types exactly, otherwise a TypeError is thrown. It applies per file and helps catch bugs early by preventing implicit type conversion.

What are return type declarations in PHP

Return type declarations specify the expected type of value a function must return. You define it after the function signature using a colon followed by the type. PHP enforces that the returned value matches this type, otherwise it throws a TypeError. This improves code reliability and makes function behavior clear.

function add(int $a, int $b): int {
    return $a + $b;
}

What are the different types of arrays in PHP

PHP supports indexed arrays, associative arrays, and multidimensional arrays

What is the difference between indexed and associative arrays

Indexed arrays use numeric keys while associative arrays use named keys

How do you add and remove elements from an array

Use [] or array_push to add and unset or array_pop to remove

What is the difference between array_merge and the + operator

array_merge reindexes numeric keys and overwrites string keys while + keeps original keys and ignores duplicates

How does PHP handle array copying

Arrays use copy-on-write so no real copy happens until modification

What is the difference between in_array and array_search

in_array returns a boolean while array_search returns the key or false

What is the difference between isset and array_key_exists

isset returns false if the value is null while array_key_exists checks if the key exists regardless of value

What are array_map and array_filter used for

array_map applies a function to each element while array_filter filters elements based on a condition

What is the difference between sort and asort

sort reindexes and sorts values while asort keeps keys and sorts values

How do you remove duplicate values from an array

Use array_unique

What is a common mistake with array_search

Using == instead of === because 0 can be treated as false

How do you loop through an array efficiently

Use foreach for simplicity and fewer errors

What is the difference between count and sizeof

No difference since sizeof is an alias of count

How do you check if a variable is an array

Use is_array

What is the difference between array_slice and array_splice

array_slice returns a portion without modifying the original while array_splice modifies the original array

What will this return

$arr = [1,2,3];
$arr2 = $arr;
$arr2[0] = 100;
print_r($arr);

[1,2,3]

What are superglobals in PHP

Superglobals are predefined global arrays that are accessible from any scope in a PHP script

What are the main PHP superglobals

$GLOBALS, $_SERVER, $_GET, $_POST, $_REQUEST, $_FILES, $_COOKIE, $_SESSION, $_ENV

What is $GLOBALS used for

It stores all global variables and allows access to them inside functions

What is $_SERVER used for

It contains server and request information like headers, script path, and request method

What is the difference between $_GET and $_POST

$_GET sends data via URL while $_POST sends data in the request body

What is $_REQUEST

It is a combination of $_GET, $_POST, and $_COOKIE but its usage is not recommended due to ambiguity

What is $_FILES used for

It handles file uploads and provides file name, type, size, and temporary path

What is $_SESSION used for

It stores user data across multiple pages on the server side

What is $_COOKIE used for

It stores small pieces of data on the client side in the browser

What is $_ENV used for

It contains environment variables from the server

What is a common security issue with superglobals

Trusting user input directly without validation or sanitization

What is the difference between $GLOBALS and global keyword

$GLOBALS is an array to access global variables while global keyword imports them into local scope

How do you secure data coming from $_GET or $_POST

Use validation, sanitization, and prepared statements to prevent attacks like SQL injection and XSS

What is a regular expression in PHP

A regular expression is a pattern used to match, search, and manipulate strings

What are the main regex functions in PHP

preg_match, preg_match_all, preg_replace, preg_split, preg_grep

What does preg_match do

It checks if a pattern matches a string and returns 1 or 0

preg_match("/php/i", "I love PHP");

What is the difference between preg_match and preg_match_all

preg_match returns the first match
preg_match_all returns all matches

What does preg_replace do

It replaces matches with a new value

echo preg_replace("/dog/", "cat", "dog is here");

What does preg_split do

It splits a string using a regex pattern

print_r(preg_split("/,/", "a,b,c"));

What does preg_grep do

It filters array elements based on a regex pattern

What are delimiters in regex

They are characters that wrap the pattern like /pattern/

What does the i modifier do

Makes the pattern case insensitive

What does ^ and $ mean

^ matches start of string
$ matches end of string

What is the difference between . and .*

. matches a single character
.* matches zero or more characters

What is a common mistake in regex

Forgetting to escape special characters like . or *

What is the difference between greedy and lazy matching

Greedy matches as much as possible
Lazy matches as little as possible

What will this return

preg_match("/^a/", "apple");

1

What is a form in PHP

A form is used to collect user input and send it to the server for processing

What is the difference between GET and POST in forms

GET sends data in the URL and is limited in size
POST sends data in the request body and supports larger data

What is the action attribute in a form

It defines the URL where the form data is sent

What is the method attribute in a form

It defines how the data is sent, usually GET or POST

How do you access form data in PHP

Using $_GET or $_POST depending on the method

$name = $_POST['name'];

What is a common security issue with forms

Trusting user input without validation or sanitization

How do you validate form data in PHP

Check required fields, data types, and formats using functions like filter_var

What is the difference between client-side and server-side validation

Client-side runs in the browser
Server-side runs in PHP and is required for security

What is CSRF and how do you prevent it

CSRF is a request forgery attack
Prevent it using tokens stored in session and validated on submit

What is XSS and how do you prevent it

XSS injects malicious scripts
Prevent it using htmlspecialchars when outputting data

echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

What is enctype in forms

It defines how form data is encoded
multipart/form-data is required for file uploads

What is the role of $_FILES in forms

It handles uploaded files and provides file details

What is a common mistake when handling forms

Not validating or sanitizing input before using it

What is the PRG pattern

Post Redirect Get prevents form resubmission by redirecting after POST

What will this return

if (empty($_POST['name'])) {
    echo "Required";
}

Required if name is empty or not set

What are date and time functions in PHP

They are used to create, format, and manipulate dates and times

What does date() function do

Formats a timestamp into a readable date string

echo date("Y-m-d"); // 2026-05-02

What is a timestamp in PHP

It is the number of seconds since January 1 1970

echo time();

What is the difference between date() and DateTime

date() is procedural and simple
DateTime is object-oriented and more flexible

$dt = new DateTime();
echo $dt->format("Y-m-d");

How do you set timezone in PHP

Use date_default_timezone_set

date_default_timezone_set("Europe/Berlin");

What does strtotime() do

Converts a readable date string into a timestamp

echo strtotime("next Monday");

How do you add or subtract time

Use strtotime or DateTime modify

echo date("Y-m-d", strtotime("+1 day"));

What is DateInterval

Represents a time interval

$dt = new DateTime();
$dt->add(new DateInterval("P1D"));

What is DatePeriod

Used to iterate over a range of dates

What is the difference between gmdate and date

date uses local timezone
gmdate uses UTC

What is a common mistake with date and time

Not setting timezone which leads to wrong values

What will this return

echo date("Y", strtotime("2000-01-01"));

2000

What is the difference between include and require in PHP

Both are used to include files but they handle errors differently. include shows a warning if the file is missing and the script continues while require throws a fatal error and stops execution

When should you use include

Use it for optional files where failure should not stop the script

When should you use require

Use it for critical files like config or core logic that must exist

What are include_once and require_once

They ensure the file is included only once and prevent duplicate declarations

What is a common mistake with include and require

Including the same file multiple times without using _once which can cause redeclaration errors

What will happen here

require "config.php";
require "config.php";

Fatal error if config.php defines functions or classes again

What is a file in PHP

A file is a resource used to store data that PHP can read from or write to on the server

How do you open a file in PHP

Use fopen with a file path and mode

$file = fopen("test.txt", "r");

What are common file modes

r read only
w write and overwrite
a append
x create new file
r+ read and write

How do you read a file

Use fread or fgets

$content = fread($file, filesize("test.txt"));

How do you write to a file

Use fwrite

fwrite($file, "Hello");

How do you close a file

Use fclose

fclose($file);

What is file_get_contents

Reads entire file into a string

echo file_get_contents("test.txt");

What is file_put_contents

Writes data to a file in one step

file_put_contents("test.txt", "Hello");

What is a common mistake with file handling

Not checking if the file exists or if fopen failed

What will this return

echo file_exists("test.txt");

true or false depending on file existence

What are cookies and sessions in PHP

They are used to store user data across requests. Cookies store data on the client side while sessions store data on the server side

What is a cookie

A small piece of data stored in the browser and sent with each request

setcookie("user", "Amr", time() + 3600);

How do you access cookies

Using $_COOKIE

echo $_COOKIE['user'];

What is a session

A server-side storage mechanism that keeps user data across multiple pages

session_start();
$_SESSION['user'] = "Amr";

How do you access session data

Using $_SESSION after calling session_start

What is the difference between cookies and sessions

Cookies are stored on the client and can be modified by the user
Sessions are stored on the server and are more secure

What is a common security issue with cookies

Storing sensitive data without encryption

How do you destroy a session

Use session_unset and session_destroy

session_start();
session_unset();
session_destroy();

What is a common mistake with sessions

Forgetting to call session_start before using $_SESSION

What is the role of session ID

It identifies the user session and is usually stored in a cookie

Continue Your PHP Interview Preparation

If you found this guide helpful, don’t miss the rest of our comprehensive PHP interview series:

By going through the full series, you’ll build a strong foundation in PHP and be fully prepared to tackle interviews with confidence.

Amr Abdelkarem

I’m Amr Abdelkarem, a PHP Backend Developer with 5+ years of experience building backend-driven systems using PHP, REST APIs, MySQL, and PostgreSQL. I’ve worked on e-commerce workflows, payment integrations, shipping automation, and scalable business logic in production environments. I also have previous experience with WordPress backend development and Django-based systems, and I’m currently focused on Laravel and backend architecture. My certifications include IBM’s Developing Front-End Apps with React, plus certifications in Cloud Computing, HTML/CSS/JavaScript, Software Engineering, Python for Data Science, and Databases and SQL.

No Comments

Leave a Comment

Course Recommendations