PHP & MySQLi Interview Questions and Answers

Answer : PHP (PHP: Hypertext Preprocessor) is a free, open source, server-side scripting language for dynamic web pages. It runs on all major platforms and web servers, supports many databases, has a huge built-in function library, supports procedural and object-oriented programming, and in PHP 8 adds a JIT compiler, union types, named arguments, match, enums and readonly properties.

Answer : Both output text. echo can take several comma-separated arguments and returns nothing; print takes one argument and always returns 1, so it can be used in expressions.

Answer : == compares values after type juggling (5 == "5" is true); === compares value and type (5 === "5" is false). In PHP 8, comparisons between numbers and non-numeric strings compare as strings, so 0 == "abc" is false.

Answer : Built-in arrays available in every scope without the global keyword: $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_ENV and $GLOBALS.

Answer : Both insert another file. If the file is missing, include gives a warning and the script continues, require gives a fatal error and stops. The _once versions load a file only once.

Answer : Cookies store small amounts of data on the client and can be changed by the user; sessions store data on the server and send only a session id (usually in the PHPSESSID cookie) to the client, so they are more secure and can hold more data.

Answer : Use prepared statements with placeholders – mysqli_prepare()/bind_param()/execute(), $conn->prepare(), or $conn->execute_query() in PHP 8.2 – so user data is never concatenated into SQL; also validate input and use a database user with limited privileges.

Answer : Escape all output that contains user data with htmlspecialchars() (or a template engine that does it automatically), validate input, and set the httponly flag on session cookies.

Answer : With password_hash($password, PASSWORD_DEFAULT), which produces a salted bcrypt/Argon2 hash, and checked with password_verify(). Never store plain text or use md5()/sha1().

Answer : The mysql extension was deprecated in PHP 5.5 and removed in PHP 7.0 because it lacked prepared statements and modern features. It is replaced by MySQLi (procedural and object-oriented) and PDO.

Answer : They offer the same features. Procedural uses functions with the connection as first argument (mysqli_query($conn, $sql)); OOP uses methods and properties of mysqli, mysqli_result and mysqli_stmt objects ($conn->query($sql), $result->num_rows). Choose one style consistently.

Answer : The default report mode became MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT, so errors throw mysqli_sql_exception instead of returning false; code should use try/catch.

Answer : A group of SQL statements that succeed or fail together, controlled with begin_transaction(), commit() and rollback() on InnoDB tables – for example when money is moved between two accounts or an order and its items are saved together.

Answer : An abstract class can contain properties and implemented methods and a class may extend only one; an interface declares only public method signatures and constants, and a class may implement many interfaces.

Answer : Reusable groups of methods that can be inserted into any class with the use keyword, providing horizontal code reuse in a single-inheritance language.

Answer : GET sends data in the URL – visible, bookmarkable, limited in size, for reading data; POST sends data in the request body – not shown in the URL, suitable for large data, files and changes to data.

Answer : Model-View-Controller, an architectural pattern separating data and business logic (model), presentation (view) and request handling (controller), used by frameworks such as Laravel and Symfony.

Answer : AJAX updates part of a page by sending HTTP requests from JavaScript (XMLHttpRequest or fetch) in the background. PHP scripts receive these requests, query the database and return HTML fragments, XML or JSON (json_encode).

Answer : A free cross-platform package from Apache Friends containing Apache, MariaDB, PHP, Perl, phpMyAdmin and other tools. It is used to develop and test PHP applications on a local computer, not as a production server.

Answer : Composer is PHP's dependency manager; it installs libraries and generates an autoloader that loads classes automatically according to the PSR-4 standard, which maps namespaces to directories.
Ch-1 : AMP Basics : AMP Basics – Apache, MySQL and PHP

Read the notes, run the programs & take the MCQ test »

Answer : AMP stands for Apache, MySQL and PHP – the web server, the database server and the server-side scripting language used together to build dynamic web sites. On Linux the stack is called LAMP, on Windows WAMP, and the cross-platform package is XAMPP.

Answer : Open source software is software whose source code is publicly available, so that anyone may use, study, modify and redistribute it according to its licence. Programmers all over the world contribute fixes and improvements, so good programs become better over time.

Answer : It was coined in 1998, after Netscape announced it would publish the source code of its Navigator browser. Long-time supporters of the idea then formed the Open Source Initiative (OSI) and wrote the Open Source Definition.

Answer : The OSI is the organisation that maintains the Open Source Definition and approves licences that meet it. Software released under an OSI-approved licence can be considered open source.

Answer : They are free; they are cross-platform and technology-neutral; they must not restrict other software distributed with them; and they embrace diversity – they cannot discriminate against any person, group or field of endeavour.

Answer : Linux is considered the first open source operating system, with BSD (distributed from Berkeley in 1989) as a close runner-up.

Answer : Apache is the chef who prepares whatever is requested, PHP is the waiter who carries the request and instructions, and MySQL is the stockroom that holds the ingredients – the data.

Answer : Apache is a web (HTTP) server. Its main job is to receive requests from browsers, parse the requested file and send the correct result back to the browser.

Answer : Password-protected pages, customised error pages, usage and error logs in customisable formats, virtual hosting of several sites on one server, directory index directives and URL rewriting (any four).

Answer : PHP stands for "PHP: Hypertext Preprocessor". It is recursive because the first word of the expansion is the acronym itself.

Answer : PHP is a server-side language. The script is executed on the web server and only the resulting HTML is sent to the browser, so visitors cannot see the PHP code.

Answer : MySQL is an open source relational database management system that uses Structured Query Language (SQL). It stores data in related tables and is designed for heavy loads and complex queries.

Answer : MariaDB is a community-developed fork of MySQL made by MySQL's original developers. It is a drop-in replacement – the same SQL and the same PHP functions work – and XAMPP has shipped MariaDB instead of MySQL since 2015.

Answer : A local installation lets you develop and test every change on your own computer without uploading files after each step. You should still test again on the live server because its settings may differ.

Answer : The browser sends an HTTP request to Apache; Apache passes the .php file to the PHP engine; PHP runs the script and sends an SQL query to MySQL/MariaDB; the database returns rows; PHP builds an HTML page; Apache sends that HTML back to the browser, which displays it.
MCQ Answer Key
No.QuestionCorrect Answer
1The term "open source" was coined in:C. 1998
2In the AMP restaurant analogy, PHP plays the role of the:B. Waiter
3Which component of the AMP stack is the web server?C. Apache
4PHP: Hypertext Preprocessor is an example of a:A. Recursive acronym
5Which database server does current XAMPP actually ship under the "MySQL" label?D. MariaDB
Ch-2 : XAMPP : XAMPP – Installation, Configuration and Use

Read the notes, run the programs & take the MCQ test »

Answer : XAMPP is a free, open source, cross-platform package from Apache Friends that installs a complete local web development server – Apache, MariaDB, PHP, Perl, phpMyAdmin and other tools – with little or no configuration.

Answer : X = cross-platform, A = Apache, M = MariaDB (originally MySQL), P = PHP, P = Perl.

Answer : Apache 2.4.58, MariaDB 10.4.32, PHP 8.2.12 and phpMyAdmin 5.2.1.

Answer : XAMPP is configured for convenience, not security: many security features are disabled, the MariaDB root user has no password and error messages are displayed in the browser. It is intended only for development and testing.

Answer : Windows User Account Control restricts writing in Program Files, so XAMPP could not write its logs, temporary files and database files there. C:\xampp avoids these permission problems.

Answer : htdocs is Apache's document root in XAMPP (C:\xampp\htdocs). Every file placed there can be opened through http://localhost/; for example C:\xampp\htdocs\a\b.php is http://localhost/a/b.php.

Answer : Service (install the module as a Windows service), Module (server name, green when running), PID(s), Port(s), and the action buttons Start/Stop, Admin, Config and Logs.

Answer : Apache's Admin opens the XAMPP dashboard at http://localhost/; MySQL's Admin opens phpMyAdmin at http://localhost/phpmyadmin/.

Answer : Apache uses port 80 for HTTP and 443 for HTTPS; MySQL (MariaDB) uses port 3306.

Answer : Use Netstat to find the program using port 80 (for example IIS, Skype or VMware) and stop it, or change Apache's port by editing Listen and ServerName in httpd.conf (e.g. to 8080) and the Control Panel's port settings, then open http://localhost:8080/.

Answer : C:\xampp\php\php.ini (Config → PHP (php.ini) in the Control Panel). After editing it you must stop and start Apache so that PHP reloads the settings.

Answer : In php.ini set date.timezone=Asia/Kolkata and restart Apache. Alternatively call date_default_timezone_set("Asia/Kolkata") at the top of a script.

Answer : In phpMyAdmin → User accounts → root → Change password set the new password; then write the same password in $cfg['Servers'][$i]['password'] in C:\xampp\phpMyAdmin\config.inc.php, and use it in PHP connection code.

Answer : A virtual host lets Apache serve a project under its own host name (e.g. phpbook.test). Add a <VirtualHost> block with ServerName and DocumentRoot in httpd-vhosts.conf, map the name to 127.0.0.1 in the Windows hosts file, and restart Apache.

Answer : Because the file was not processed by Apache/PHP: it was opened directly from disk (file:///) or saved with a non-.php extension. Save it as .php inside htdocs and open it through http://localhost/.
MCQ Answer Key
No.QuestionCorrect Answer
1In XAMPP, the "M" now stands for:B. MariaDB
2The default web root folder of XAMPP on Windows is:C. C:\xampp\htdocs
3The default port of MySQL/MariaDB in XAMPP is:D. 3306
4Which file must be edited to change the PHP upload limit?C. php.ini
5Which Control Panel button shows which program is using a port?A. Netstat
Ch-3 : Introduction & Syntax : PHP – Hypertext Preprocessor: Introduction and Syntax

Read the notes, run the programs & take the MCQ test »

Answer : PHP (PHP: Hypertext Preprocessor) is a free, open source, server-side scripting language used to create dynamic web pages. Scripts run on the web server and generate HTML that is sent to the browser.

Answer : PHP was created by Rasmus Lerdorf in 1995. It was later rewritten by Andi Gutmans and Zeev Suraski (PHP 3, 1998), whose Zend Engine powers PHP 4 and later.

Answer : Because PHP runs on the server. The server executes the script and sends only its output – usually HTML – to the browser, so View Source shows the generated HTML, not the PHP code.

Answer : MySQL/MariaDB, PostgreSQL, Oracle, SQLite, Microsoft SQL Server and any ODBC data source (any four).

Answer : A PHP file can contain plain text, HTML tags and PHP script blocks. It uses the .php extension so that the web server passes it to the PHP engine.

Answer : It starts with <?php and ends with ?>. A block can appear anywhere in the document and a file can contain many blocks.

Answer : The semicolon is the statement separator. Every PHP statement must end with a semicolon so that PHP can tell one instruction from the next.

Answer : The server does not pass it to the PHP engine, so the PHP code is not executed; the browser treats it as plain HTML/text.

Answer : echo can output one or more comma-separated strings and has no return value; print outputs exactly one string and always returns 1, so it can be used in expressions. echo is marginally faster.

Answer : <?= expression ?> is a shortcut for <?php echo expression; ?>. It is always available since PHP 5.4 and is convenient inside HTML templates.

Answer : It only works when short_open_tag is enabled in php.ini, so the code is not portable between servers. The standard <?php tag always works.

Answer : // single-line comment, # single-line comment, and /* ... */ multi-line comment.

Answer : Partly. Keywords, function names and class names are case-insensitive (ECHO = echo), but variable names are case-sensitive ($name and $Name are different variables). Constants are case-sensitive too.

Answer : In files that contain only PHP code. Omitting it prevents accidental white space after ?> from being sent as output, which would cause "headers already sent" errors with header(), setcookie() or session_start().

Answer : The JIT compiler, named arguments, union types, the match expression, the nullsafe operator ?-> and (in 8.1) enums – any three.
MCQ Answer Key
No.QuestionCorrect Answer
1PHP code is executed:B. On the web server
2Which tag correctly starts a portable PHP block?A. <?php
3Which statement about print is TRUE?B. It always returns 1
4Which of these is case-sensitive in PHP?C. Variable names
5Which symbol does NOT start a comment in PHP?D. <!--
Ch-4 : Constants, Variables & Data Types : Constants, Variables and Data Types

Read the notes, run the programs & take the MCQ test »

Answer : A constant is a named value that cannot change during script execution. It is defined with define("NAME", value) or with const NAME = value; and used without a $ sign.

Answer : A constant name must start with a letter or underscore, may contain letters, digits and underscores, and is case-sensitive. By convention constants are written in capital letters.

Answer : A variable is a named storage location for a value such as a string, number or array. Every variable name starts with the $ sign, e.g. $total = 100;

Answer : Because a variable does not need to be declared with a type; PHP decides the type from the assigned value and can convert it automatically when needed.

Answer : The name must start with a letter or underscore after $, may contain only letters, digits and underscores, must not contain spaces, and is case-sensitive.

Answer : int (integer), float (double), string and bool (boolean).

Answer : echo only prints the value; var_dump() prints the data type, the length (for strings/arrays) and the value, which is useful for debugging.

Answer : The automatic conversion of a value from one type to another depending on context, e.g. "10" + 5 gives the integer 15 because the + operator needs numbers.

Answer : With a cast: (int) $value, or with the function intval($value). For example (int) 12.9 gives 12.

Answer : A variable created inside a function is local and exists only in that function. A variable created outside functions is global and is not visible inside functions unless brought in with the global keyword or accessed via $GLOBALS.

Answer : A variable declared with the static keyword inside a function keeps its value between calls of that function instead of being re-initialised each time.

Answer : A php.ini setting that turned request data (form fields, URL parameters, cookies) into ordinary variables automatically. Attackers could inject values into program variables, so it was disabled by default from PHP 4.2 and removed in PHP 5.4.

Answer : Built-in associative arrays that are available in every scope, such as $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_ENV and $GLOBALS.

Answer : $_GET holds values sent in the URL query string (form method="get"); $_POST holds values sent in the body of an HTTP POST request (form method="post").

Answer : $_SERVER – for example $_SERVER['PHP_SELF'] gives the script path and $_SERVER['REQUEST_METHOD'] gives GET or POST.
MCQ Answer Key
No.QuestionCorrect Answer
1Which is a valid variable name?C. $_first_name
2A constant created with define() is used:B. Without a $ prefix
3What does "10" + 5 evaluate to?B. 15
4A variable that keeps its value between function calls is declared with:B. static
5In which PHP version was register_globals removed?C. 5.4
Ch-5 : Operators : Operators and Expressions

Read the notes, run the programs & take the MCQ test »

Answer : An operator is a symbol that performs an operation, such as + or ==. The values or variables it works on are its operands; in $a + $b, $a and $b are operands.

Answer : + addition, - subtraction, * multiplication, / division, % modulus (remainder) and ** exponentiation; unary - negates a value.

Answer : 2, because % returns the remainder of the integer division: 17 = 3 × 5 + 2.

Answer : == (equal) compares values after type juggling, so 5 == "5" is true. === (identical) is true only when the values are equal and of the same type, so 5 === "5" is false.

Answer : $a <=> $b returns -1 if $a is less than $b, 0 if they are equal and 1 if $a is greater. It is useful in sorting callbacks.

Answer : && (and) is true when both operands are true; || (or) when at least one is true; xor when exactly one is true; ! (not) reverses true and false.

Answer : ++$v adds 1 first and returns the new value; $v++ returns the current value and then adds 1. With $v = 5, echo $v++ prints 5 and echo ++$v prints the incremented value.

Answer : The concatenation operator, a period (.), e.g. "PHP" . " 8" gives "PHP 8". The .= operator appends to an existing string variable.

Answer : Operators that combine an operation with assignment: $a += 5 means $a = $a + 5; similarly -=, *=, /=, %= and .=.

Answer : A shorthand if-else expression: condition ? value_if_true : value_if_false. Example: $r = ($marks >= 40) ? "Pass" : "Fail";

Answer : ?? returns its left operand if it exists and is not null, otherwise its right operand. $name = $_GET['name'] ?? 'Guest'; avoids warnings for missing form fields.

Answer : The rank that decides which operator is evaluated first in an expression without parentheses; e.g. * has higher precedence than +, so 2 + 3 * 3 = 11.

Answer : The rule for evaluating operators of equal precedence. Left-associative operators (like + and -) are evaluated left to right, so 7 - 4 + 1 = 4; right-associative ones (like = and **) are evaluated right to left.

Answer : (1 + (3 + 3)) * 2 = 7 × 2 = 14. 1 + 3 + 3 * 2 = 1 + 3 + 6 = 10.

Answer : They make the intended order of evaluation obvious to anyone reading the code and protect against precedence mistakes, without changing correct results.
MCQ Answer Key
No.QuestionCorrect Answer
1What is the value of 2 + 3 * 3?B. 11
25 === "5" evaluates to:B. false
3If $v = 5, what does echo $v++; print?B. 5
4Which operator appends a string to a variable?C. .=
5$name = $_GET['name'] ?? 'Guest'; uses the:B. Null coalescing operator
Ch-6 : Conditional Statements : Conditional Statements

Read the notes, run the programs & take the MCQ test »

Answer : Statements that let a program take different actions depending on whether a condition is true or false: if, if…else, if…elseif…else, switch and match.

Answer : if (condition) { statements; } – the statements run only when the condition evaluates to true.

Answer : When more than one statement must be executed for a branch. Without braces only the first statement belongs to the if/else. Using braces always is a good habit.

Answer : if…else chooses between exactly two blocks. if…elseif…else tests several conditions in turn and runs the block of the first true condition, or the else block if none is true.

Answer : The three-letter textual name of the current day, from Mon to Sun.

Answer : An if statement placed inside another if or else block, used when a second decision depends on the first, e.g. checking citizenship only for people aged 18 or over.

Answer : The expression is evaluated once and its value compared with each case label. When a match is found, the statements of that case run until a break; if no case matches, the default block runs.

Answer : break ends the switch. Without it execution continues ("falls through") into the next case's statements.

Answer : It is executed when the switch expression matches none of the case labels – like the else of an if statement.

Answer : When several case values need the same code, e.g. case 4: case 6: case 9: case 11: $days = 30; break;

Answer : match is an expression that returns a value, compares with strict ===, allows several comma-separated conditions per arm, needs no break, and throws UnhandledMatchError when nothing matches and there is no default.

Answer : PHP 8.0.

Answer : Replacing the opening brace with a colon and the closing brace with endif;, endswitch;, endfor;, endforeach; or endwhile; – useful when mixing PHP with HTML.

Answer : Yes. switch ($day) { case "Sat": case "Sun": echo "Weekend"; break; default: echo "Weekday"; } works with strings as well as numbers.

Answer : if ($marks >= 40) { echo "Pass"; } else { echo "Fail"; } – or with the ternary operator: echo $marks >= 40 ? "Pass" : "Fail";
MCQ Answer Key
No.QuestionCorrect Answer
1Which statement selects one of many blocks by comparing one value with several labels?B. switch
2What happens if break is omitted at the end of a case?C. Execution falls through to the next case
3Which keyword introduces an extra condition after if?B. elseif
4The PHP 8 match expression compares values using:B. ===
5Which closes an if block written in alternative syntax?C. endif;
Ch-7 : Loops : Looping Statements

Read the notes, run the programs & take the MCQ test »

Answer : A control structure that executes a block of code repeatedly – a fixed number of times or while a condition is true.

Answer : while, do…while, for and foreach.

Answer : while (condition) { statements; } – the condition is tested before every iteration; the body repeats while it is true and is skipped entirely if it is false at the start.

Answer : do…while tests the condition after the body, so the body always executes at least once (exit-controlled); while tests first (entry-controlled) and may execute zero times.

Answer : Because $i is incremented before it is printed, and the condition $i <= 5 is checked after the body, so when $i is 5 the loop runs once more, printing 6.

Answer : init runs once before the loop (e.g. $i = 1); condition is checked before each iteration ($i <= 5); increment runs at the end of each iteration ($i++).

Answer : Yes. Separate the expressions with commas: for ($i = 1, $j = 10; $i <= 10; $i++, $j--).

Answer : To iterate over every element of an array (or object), assigning each value – and optionally its key – to variables.

Answer : foreach ($array as $value) { … } and foreach ($array as $key => $value) { … }.

Answer : It terminates the loop immediately and continues with the first statement after the loop.

Answer : It skips the remaining statements of the current iteration and starts the next iteration.

Answer : A loop placed inside another loop; the inner loop completes all its iterations for each iteration of the outer loop.

Answer : A loop whose condition never becomes false, e.g. forgetting $i++ in a while loop. PHP stops such a script when max_execution_time is exceeded.

Answer : A while loop, e.g. while ($row = mysqli_fetch_assoc($result)) { … }, because the number of rows is not known in advance.

Answer : for ($i = 2; $i <= 20; $i += 2) { echo $i . " "; }
MCQ Answer Key
No.QuestionCorrect Answer
1Which loop always executes its body at least once?C. do…while
2Which loop is designed to iterate over arrays?B. foreach
3What does continue do?B. Skips to the next iteration
4How many times does for ($i = 0; $i < 5; $i++) execute its body?B. 5
5In for (init; condition; increment), the init part runs:C. Only once, before the loop starts
Ch-8 : Strings : PHP and Strings

Read the notes, run the programs & take the MCQ test »

Answer : A series of characters, where each character is one byte. Strings can hold text of any length limited only by available memory.

Answer : Four – single-quoted, double-quoted, heredoc and nowdoc.

Answer : Only \' for a literal single quote and \\ for a literal backslash. All other backslashes are printed as they are.

Answer : Double-quoted strings expand variables and interpret escape sequences such as \n and \t; single-quoted strings do neither.

Answer : Replacing variable names inside a double-quoted string or heredoc with their values, e.g. "Hello $name" becomes "Hello Asha".

Answer : For array elements with quoted string keys, object properties of objects in arrays, method calls and other complex expressions, e.g. "{$user['city']}" or "{$foo->bar[1]}".

Answer : A way of writing multi-line strings: <<<IDENTIFIER, a new line, the text, then the identifier again. It behaves like a double-quoted string, so variables are expanded and quotes need no escaping.

Answer : A heredoc whose identifier is in single quotes, e.g. <<<'EOT'. No parsing is done inside it – it behaves like a single-quoted string.

Answer : It must match the opening identifier and be the first non-white-space text on its line. Since PHP 7.3 it may be indented (that indentation is removed from all lines) and may be followed by other code; before 7.3 it had to start in column 1 with only an optional semicolon after it.

Answer : In static contexts such as initialising class properties and class constants, because nowdoc contains no variables to parse.

Answer : "\u{20B9}" inside a double-quoted string (PHP 7 and later).

Answer : strlen() counts bytes, and each Devanagari character takes several bytes in UTF-8. mb_strlen() counts characters.

Answer : strpos($s, $find) returns the position of the first occurrence of $find in $s (or false); str_replace($search, $replace, $s) replaces all occurrences of $search with $replace.

Answer : White space (spaces, tabs, new lines, NUL and vertical tab) from the beginning and end of a string; ltrim() and rtrim() remove it from one side only.

Answer : str_contains($haystack, $needle), which returns true or false. PHP 8 also added str_starts_with() and str_ends_with().
MCQ Answer Key
No.QuestionCorrect Answer
1What does echo 'Hi\n$x'; print?B. Hi\n$x
2Which string syntax does NOT expand variables?C. Nowdoc
3A nowdoc identifier is written as:C. <<<'EOT'
4What is "\x41" in a double-quoted string?B. A
5Which function counts characters correctly in UTF-8 text?C. mb_strlen()
Ch-9 : Arrays : PHP and Arrays

Read the notes, run the programs & take the MCQ test »

Answer : A special variable that stores multiple values under a single name; each value (element) is identified by an index or key.

Answer : To handle lists of related values efficiently – for example 3000 car names – so that they can be looped through, searched and sorted, instead of creating thousands of separate variables.

Answer : Numeric (indexed) arrays, associative arrays and multidimensional arrays.

Answer : >
  • The elements of array("Saab", "Volvo") have indexes 0 and 1.
  • <

    Answer : Automatically: $cars = array("Saab", "Volvo", "BMW"); or $cars = ["Saab", "Volvo", "BMW"]; and manually: $cars[0] = "Saab"; $cars[1] = "Volvo"; …

    Answer : An array whose keys are named strings associated with values, e.g. $ages = array("Peter" => 32, "Joe" => 34); then $ages['Peter'] is 32.

    Answer : It imports the elements of an associative array into the current symbol table: each key becomes a variable holding the element's value. It returns the number of variables created.

    Answer : A visitor could add form fields named like your variables and overwrite them – the same security problem that register_globals caused.

    Answer : An array whose elements are themselves arrays, e.g. a list of families where each family is an array of names; elements are accessed with several indexes like $families['Griffin'][2].

    Answer : With print_r($array) (human-readable) or var_dump($array) (with types and lengths), preferably inside <pre> tags in a browser.

    Answer : With count($array) (sizeof() is an alias).

    Answer : sort() sorts the values and re-indexes the array (keys are lost); asort() sorts by value but keeps each key associated with its value, suitable for associative arrays.

    Answer : ksort() for ascending order, krsort() for descending order.

    Answer : To the end with $a[] = $value; or array_push($a, $value); to the beginning with array_unshift($a, $value).

    Answer : Assigning array elements to separate variables in one statement: [$first, $second] = $colors; (or list($first, $second) = $colors;).
    MCQ Answer Key
    No.QuestionCorrect Answer
    1What is the index of "BMW" in array("Saab", "Volvo", "BMW")?B. 2
    2$ages = ["Peter" => 32]; creates a(n):B. Associative array
    3Which function converts array keys into variables?C. extract()
    4Which function sorts by value and keeps the key–value association?B. asort()
    5$families['Griffin'][2] accesses an element of a:B. Multidimensional array
    Ch-10 : User-Defined Functions : User-Defined Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : A named block of code that performs a specific task and runs only when it is called. Functions avoid repeating code and make programs modular.

    Answer : function functionName($param1, $param2) { statements; return value; }

    Answer : The name must start with a letter or underscore, may contain letters, digits and underscores, should describe what the function does, and is not case-sensitive.

    Answer : A parameter is the variable listed in the function definition; an argument is the actual value passed when the function is called.

    Answer : It ends the function and sends a value back to the caller, where it can be printed or stored, e.g. echo add(1, 16);

    Answer : By returning an array (or object) and, if desired, destructuring it: [$lo, $hi] = stats($nums);

    Answer : Values assigned to parameters in the definition, e.g. function greet($name, $greeting = "Namaste"), used when the caller omits that argument. They must come after required parameters.

    Answer : Call by value passes a copy, so changes inside the function do not affect the original variable. Call by reference (parameter written as &$n) passes the variable itself, so changes are visible to the caller.

    Answer : Declarations of the expected parameter and return types, e.g. function area(float $l): float. With declare(strict_types=1) PHP throws a TypeError for values of the wrong type.

    Answer : A PHP 8 feature that lets you pass arguments by parameter name, in any order, and skip optional parameters: format(1234.5, prefix: "Rs. ").

    Answer : A function that accepts any number of arguments using the ... operator, e.g. function total(...$numbers), where $numbers becomes an array.

    Answer : Recursion is a function calling itself. A base case is a condition that returns without calling again; without it the function would call itself forever until memory runs out.

    Answer : A function without a name, created with function (…) { … } and stored in a variable or passed as an argument (a closure). The use keyword imports outer variables into it.

    Answer : A short closure introduced in PHP 7.4: fn($x) => $x * 2. It has a single expression body and automatically captures variables from the outer scope by value.

    Answer : When a variable contains the name of a function, adding parentheses calls that function: $f = "strtoupper"; echo $f("php");
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which keyword defines a function?C. function
    2How do you pass a parameter by reference?B. &$n
    3What does function greet($n, $g = "Hi") mean?B. $g is optional with default "Hi"
    4Which PHP 8 feature allows format(1234.5, prefix: "Rs. ")?B. Named arguments
    5Which is an arrow function?B. fn($x) => $x * 2
    Ch-11 : Form Handling : PHP Form Handling

    Read the notes, run the programs & take the MCQ test »

    Answer : Every form field with a name attribute is sent to the script named in the form's action attribute and is available in $_POST, $_GET or $_REQUEST, with the field name as the key.

    Answer : action gives the URL of the script that processes the data; method specifies how the data is sent – GET (in the URL) or POST (in the request body).

    Answer : A superglobal associative array containing the variables passed in the URL query string, for example from a form with method="get".

    Answer : The field names and values are appended after a question mark and separated by &, e.g. welcome_get.php?fname=Peter&age=37.

    Answer : For requests that only read data, such as searches and filters, where bookmarking the result page is useful – never for passwords or sensitive data, and only for small amounts of data.

    Answer : A superglobal associative array containing the variables sent in the body of an HTTP POST request, for example from a form with method="post".

    Answer : Data is not shown in the URL, there is no practical size limit (only post_max_size), and it can carry binary data such as uploaded files.

    Answer : post_max_size (XAMPP sets 40M; PHP's default is 8M). upload_max_filesize limits each uploaded file.

    Answer : A superglobal array that contains the contents of $_GET, $_POST and $_COOKIE together, so a script can read a value without caring how it was sent.

    Answer : XSS happens when user-supplied HTML/JavaScript is output into a page and runs in other users' browsers. Prevent it by escaping output with htmlspecialchars().

    Answer : A form whose action is the same script (e.g. htmlspecialchars($_SERVER['PHP_SELF'])). The script shows the form and, when $_SERVER['REQUEST_METHOD'] is POST, processes the submitted data on the same page.

    Answer : Name the checkboxes with square brackets, e.g. name="hobby[]"; PHP then provides $_POST['hobby'] as an array of the checked values.

    Answer : Unchecked checkboxes, unselected radio buttons and fields of a form that was not submitted are not sent at all; reading them directly would cause "Undefined array key" warnings.

    Answer : Because an attacker can add text to the URL path that is reflected in the page; htmlspecialchars() prevents this from being interpreted as HTML/JavaScript.

    Answer : No. The posted values are not part of the URL, so a bookmark would load the page without them.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which array holds values sent by a form with method="post"?B. $_POST
    2Which method displays form data in the browser's address bar?C. GET
    3$_REQUEST contains the contents of:B. $_GET, $_POST and $_COOKIE
    4Which function protects output against XSS?B. htmlspecialchars()
    5To receive several checked checkboxes as an array, the field name should be:B. hobby[]
    Ch-12 : Form Validation & RegEx : Form Validation and Regular Expressions

    Read the notes, run the programs & take the MCQ test »

    Answer : Browser validation can be disabled or bypassed (for example by sending a request directly), so only server-side validation guarantees that bad or malicious data does not reach the program or database.

    Answer : The errors can be displayed next to the fields on the same page, together with the values already typed, so the user can correct them easily.

    Answer : A pattern, written in a special syntax, that describes a set of strings. It is used to search, validate, replace and split text.

    Answer : The characters that enclose the pattern, usually slashes: "/abc/". Flags such as i (case-insensitive) follow the closing delimiter.

    Answer : * means zero or more occurrences, + one or more, and ? zero or one (optional) of the preceding item.

    Answer : The preceding item must occur at least 2 and at most 4 times.

    Answer : ^ anchors the match to the start of the string and $ to the end. Inside a character class, ^ as the first character negates the class.

    Answer : A set of characters in square brackets that matches any one of them: [aeiou] a vowel, [0-9] a digit, [A-Za-z] a letter, [^0-9] any non-digit.

    Answer : \d a digit, \w a word character (letter, digit or underscore), \s a white-space character. The uppercase forms \D, \W, \S match the opposites.

    Answer : 1 if the pattern matches, 0 if it does not (and false on error). The matched text is stored in the optional $matches array.

    Answer : preg_match() stops at the first match; preg_match_all() finds every match in the subject and returns the number of matches.

    Answer : $1, $2 … in the replacement string refer to the text captured by the first, second … parenthesised groups of the pattern; $0 is the whole match.

    Answer : /e evaluated the replacement as PHP code, which allowed code injection. It was removed in PHP 7.0; preg_replace_callback() calls a function for each match instead.

    Answer : It splits a string into an array wherever the pattern matches, e.g. preg_split("/[\s,]+/", $text) splits at any run of commas or white space.

    Answer : The elements of an array that match the pattern, keeping their original keys.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1The quantifier + means:C. 1 or more
    2Which pattern matches exactly ten digits?A. /^\d{10}$/
    3What does preg_match() return when no match is found?B. 0
    4Which function should replace the removed /e modifier?B. preg_replace_callback()
    5[^0-9] matches:B. Any non-digit character
    Ch-13 : include / require : Server Side Includes – include and require

    Read the notes, run the programs & take the MCQ test »

    Answer : The technique of inserting the contents of one file into another before the server executes it, using include or require, so that common parts are written once and reused.

    Answer : Both insert a file, but if the file cannot be loaded include issues a warning and the script continues, while require issues a fatal error and the script stops.

    Answer : include only produces a warning, which does not stop execution; require produces a fatal error, which terminates the script.

    Answer : Code is written once and reused; a change (e.g. to the menu) is made in one place for the whole site; pages become shorter and easier to maintain.

    Answer : It works like include but does nothing if the file has already been included in the current script, preventing redeclaration errors.

    Answer : For essential files that may be referenced from several scripts, such as a function library, class file or database connection file.

    Answer : A fatal error "Cannot redeclare function …", because the same function would be defined twice.

    Answer : No. include and require are language constructs, so include "file.php"; and include("file.php"); are equivalent.

    Answer : An array with the full paths of all files that have been included or required so far, including the main script.

    Answer : By using a return statement at its top level; for example $config = require "config.php"; receives the array returned by config.php.

    Answer : Only the final combined output; the included file's HTML appears where the include statement was, and the include itself is not visible.

    Answer : include – if the advertisement file is missing, the rest of the page is still displayed.

    Answer : In the directories listed in the include_path setting (usually including the current directory "."), and then in the calling script's own directory.

    Answer : Yes. Any text outside <?php … ?> is output as it is, so an include file may contain pure HTML, pure PHP, or a mixture.

    Answer : To avoid sending accidental white space after ?> to the browser, which could break header(), setcookie() or session_start().
    MCQ Answer Key
    No.QuestionCorrect Answer
    1If the included file is missing, include produces a:B. Warning
    2Which statement stops the script when the file cannot be loaded?C. require
    3require_once prevents:A. Loading a file more than once
    4Which is the best choice for a database connection file?B. require_once
    5What does $c = require "config.php"; store in $c?C. The value returned by config.php
    Ch-14 : File System : PHP and the File System

    Read the notes, run the programs & take the MCQ test »

    Answer : PHP runs on the server, so it has access to the server's file system; JavaScript runs in the visitor's browser and has no access to the server's files.

    Answer : A file handle (resource) used by other file functions, or false if the file cannot be opened.

    Answer : r opens for reading from the beginning; w opens for writing and clears the file (creating it if necessary); a opens for writing at the end of the file (creating it if necessary).

    Answer : w overwrites an existing file; x creates a new file and fails (returns false with a warning) if the file already exists.

    Answer : fwrite() returns the number of bytes written (false on failure). fputs() is an alias of fwrite().

    Answer : It returns true when the file pointer has reached the end of the file, so it is used to stop loops that read files of unknown length.

    Answer : fgets() reads one line, fgetc() reads one character, and fread($h, $n) reads up to $n bytes.

    Answer : With file_get_contents("file.txt"), or with fread($handle, filesize("file.txt")).

    Answer : An array containing the lines of the file, one line per element.

    Answer : method="post" and enctype="multipart/form-data", plus an <input type="file" name="…"> field.

    Answer : name (original file name), type (MIME type), size (bytes), tmp_name (temporary file on the server) and error (error code); PHP 8.1 also adds full_path.

    Answer : It stays only as a temporary file in PHP's temp folder and is deleted automatically when the script ends.

    Answer : It is supplied by the browser and can be forged. The real content should be checked on the server with mime_content_type(), finfo or getimagesize().

    Answer : file_uploads (must be On), upload_max_filesize (size of one file), post_max_size (size of the whole request) and max_file_uploads (number of files).

    Answer : UPLOAD_ERR_NO_FILE – the form was submitted without choosing a file.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which mode opens a file for writing and erases its existing content?C. w
    2Which function reads a single line from a file?B. fgets()
    3Which enctype is required for file uploads?C. multipart/form-data
    4Which function permanently saves an uploaded file?B. move_uploaded_file()
    5$_FILES["file"]["tmp_name"] contains:B. The temporary path on the server
    Ch-15 : E-Mail : PHP and E-Mail

    Read the notes, run the programs & take the MCQ test »

    Answer : mail(), with the parameters to, subject, message and the optional headers and additional parameters.

    Answer : to, subject and message. headers and parameters are optional.

    Answer : true if the message was accepted for delivery by the configured mail system, false otherwise. It does not guarantee the mail reaches the recipient.

    Answer : The subject is placed in a mail header; a newline would end the header and could be abused to inject extra headers.

    Answer : As a string with each header separated by "\r\n", e.g. "From: a@x.com\r\nCc: b@x.com", or in PHP 8 as an associative array.

    Answer : MIME-Version: 1.0 and Content-type: text/html; charset=UTF-8 (plus From).

    Answer : Cc (carbon copy) recipients are visible to all recipients; Bcc (blind carbon copy) recipients receive the mail without being shown to others.

    Answer : When first visited, $_REQUEST['email'] is not set, so the form is shown. After submission the page reloads with the field set, so the script reads email, subject and message and calls mail().

    Answer : An attack where a user enters newline characters plus extra headers (such as Bcc:) into a form field that is placed in a mail header, making the server send spam to other addresses.

    Answer : Validate the address with filter_var($email, FILTER_VALIDATE_EMAIL), reject any newline characters in fields used in headers, and never put raw user input into headers.

    Answer : It removes all characters that are not allowed in an e-mail address, before the value is validated.

    Answer : SMTP and smtp_port (the mail server), sendmail_from (default sender), or sendmail_path to use a program such as XAMPP's sendmail.exe or mailtodisk.exe.

    Answer : A tool configured through sendmail_path that saves every message sent with mail() as a file in C:\xampp\mailoutput instead of delivering it – useful for testing.

    Answer : In php.ini set sendmail_path to XAMPP's sendmail.exe; in sendmail.ini set smtp_server=smtp.gmail.com, smtp_port=587, smtp_ssl=tls, the Gmail address and a Gmail app password; then restart Apache.

    Answer : PHPMailer handles SMTP authentication, encryption, attachments, HTML/plain alternatives and error reporting much more reliably than the basic mail() function.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which parameter of mail() is optional?D. headers
    2Mail headers in a string are separated by:B. \r\n
    3Which header is needed for HTML mail?A. Content-type: text/html
    4E-mail header injection is prevented by:B. Validating fields and rejecting newlines
    5In XAMPP, mailToDisk saves messages in:B. C:\xampp\mailoutput
    Ch-16 : Namespaces : PHP Namespaces

    Read the notes, run the programs & take the MCQ test »

    Answer : A named container that groups related classes, interfaces, functions and constants, so that the same names can be used in different namespaces without colliding – similar to directories grouping files.

    Answer : Name collisions between your code, PHP's internal names and third-party code; and the need for very long names, which namespaces allow you to alias or shorten.

    Answer : PHP 5.3.

    Answer : It must be the first statement in the file; only a declare statement may precede it – no HTML or white space.

    Answer : With backslashes in the name, e.g. namespace MyProject\Sub\Level;

    Answer : Yes. Unlike other constructs, the same namespace can be declared in many files.

    Answer : Use the bracketed syntax: namespace A { … } namespace B { … } and namespace { … } for the global code.

    Answer : A qualified name contains a namespace separator but no leading backslash (Sub\Connection) and is resolved relative to the current namespace; a fully qualified name starts with \ (\MyProject\Connection) and is resolved from the global root.

    Answer : It imports a class, interface, namespace, function (use function) or constant (use const) into the current file, optionally with an alias: use My\Full\Classname as Another;

    Answer : Imports are processed at compile time, while a class name stored in a string is resolved at run time, so dynamic names must be fully qualified.

    Answer : The space where all names live when no namespace is declared. Prefix a name with \ to use the global name inside a namespace, e.g. \strlen() or \ArrayObject.

    Answer : For functions and constants, PHP first looks in the current namespace and then falls back to the global one; for classes there is no fallback.

    Answer : A magic constant containing the name of the current namespace as a string; it is empty in the global space.

    Answer : The keyword namespace used in a name to refer explicitly to the current namespace, e.g. namespace\hello() or namespace\MYCONST.

    Answer : Because PHP looks for the class Shop\ArrayObject. You must write \ArrayObject or add use ArrayObject; at the top of the file.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which keyword declares a namespace?B. namespace
    2Which separator is used in namespace names?C. \
    3\strlen("x") inside a namespace calls:B. The global strlen
    4Which statement imports a function from a namespace?C. use function MyProject\connect;
    5What is __NAMESPACE__ in the global space?C. An empty string
    Ch-17 : OOP – Classes & Objects : Object-Oriented PHP – Classes and Objects

    Read the notes, run the programs & take the MCQ test »

    Answer : A class is a blueprint or template that defines properties and methods; an object is a concrete instance of a class, created with new, with its own property values.

    Answer : Constants, properties (member variables) and methods (member functions).

    Answer : A pseudo-variable available inside non-static methods that refers to the object on which the method was called, e.g. $this->var.

    Answer : With the new keyword: $obj = new SimpleClass(); Yes – $cls = 'Foo'; $obj = new $cls(); creates a Foo object.

    Answer : A special method, __construct(), called automatically when an object is created, used to initialise the object.

    Answer : With parent::__construct(); – parent constructors are not called automatically when the child defines its own constructor.

    Answer : A method with the same name as its class is no longer treated as a constructor in PHP 8; it is an ordinary method. Only __construct() is a constructor.

    Answer : A PHP 8 feature where constructor parameters with a visibility keyword, e.g. public function __construct(public string $name), automatically declare and assign the property.

    Answer : When the last reference to the object is removed, when the object is destroyed with unset(), or at the end of the script during shutdown – even after exit().

    Answer : public members are accessible everywhere; protected only within the class and its parent/child classes; private only within the class that declares them.

    Answer : Inheritance lets a class acquire the public and protected members of another class. It is implemented with extends: class Bar extends Foo. PHP supports single inheritance.

    Answer : Re-declaring an inherited method with the same name in the child class to change its behaviour; the parent version can still be called with parent::method(). A final method cannot be overridden.

    Answer : The double colon :: used to access static properties and methods, class constants and overridden parent members, e.g. MyClass::CONST_VALUE, self::$x, parent::myFunc().

    Answer : Static properties and methods belong to the class rather than to objects and are accessed with ClassName:: or self::. $this cannot be used in a static method because there is no object.

    Answer : Loading class files automatically when a class is first used. Register a loader with spl_autoload_register(function ($class) { require $class . '.php'; }); __autoload() was removed in PHP 8.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which keyword creates an object?B. new
    2What is the name of the constructor method in PHP 8?C. __construct()
    3A protected property can be accessed from:C. The declaring class and its parent/child classes
    4Which replaces the removed __autoload() function?A. spl_autoload_register()
    5Inside a static method you cannot use:C. $this
    Ch-18 : OOP – Advanced : Object-Oriented PHP – Abstraction, Overloading, Iteration and Patterns

    Read the notes, run the programs & take the MCQ test »

    Answer : A class declared with the abstract keyword that cannot be instantiated. It may contain abstract methods (signatures only) and normal methods, and serves as a base for child classes.

    Answer : Every abstract method of the parent must be implemented in the child with a compatible signature and the same or less restrictive visibility (protected may become public, but not private).

    Answer : A contract that lists public method signatures (and constants) without implementation. A class that implements it must define all its methods.

    Answer : An abstract class can have properties and concrete methods and a class can extend only one; an interface has only method signatures and constants, and a class can implement many interfaces.

    Answer : A reusable set of methods that can be inserted into any class with the use keyword, providing code reuse without inheritance.

    Answer : A final method cannot be overridden in a child class; a final class cannot be extended.

    Answer : Dynamically creating properties and methods through magic methods that are called when inaccessible (undeclared or invisible) properties or methods are used.

    Answer : __set() when a value is written to an inaccessible property; __get() when an inaccessible property is read.

    Answer : __isset() when isset() or empty() is used on an inaccessible property; __unset() when unset() is used on one.

    Answer : __call() is triggered when an inaccessible method is called on an object; __callStatic() when an inaccessible method is called statically on the class.

    Answer : All visible properties – from outside the class only public ones, from inside the class also protected and private ones.

    Answer : current(), key(), next(), rewind() and valid().

    Answer : An interface with a single method, getIterator(), which returns an iterator; it lets a class be used in foreach without implementing all Iterator methods.

    Answer : A design pattern in which a method creates and returns objects of a class chosen at run time, e.g. Example::factory('MySQL') loads and instantiates Driver_MySQL.

    Answer : It ensures that only one instance of a class exists. The constructor and __clone() are private, the instance is stored in a private static property, and a public static method creates it on first call and returns it afterwards.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1An abstract class:B. Cannot be instantiated
    2A class can implement:B. Many interfaces
    3Which magic method runs when a value is written to an inaccessible property?B. __set()
    4Which interface needs only the getIterator() method?C. IteratorAggregate
    5The Singleton pattern makes the constructor:C. private
    Ch-19 : MVC : PHP and MVC (Model–View–Controller)

    Read the notes, run the programs & take the MCQ test »

    Answer : Model–View–Controller, an architectural pattern that separates an application into the model (data and business logic), the view (presentation) and the controller (handling of user input).

    Answer : PHP is so easy to use that it is easy to write unstructured code mixing SQL, logic and HTML. Unlike Java or C++, it does not force good design, so self-discipline through patterns like MVC is needed.

    Answer : A description of a reusable, tried-and-tested solution to a recurring design problem in a particular context.

    Answer : The model is the heart of the application – the classes that retrieve and manipulate data, apply business rules and talk to the database, independent of how data is displayed.

    Answer : The view presents the data supplied by the model to the user in a form suitable for the device and renders the controls for further input.

    Answer : The controller receives the user's input (links, forms) and passes requests or data to the model, deciding which view to show.

    Answer : The fourth component that glues model, view and controller together – in PHP typically a front script that includes the right classes and template.

    Answer : Components are interchangeable (e.g. a new view for mobiles), code is easier to debug and maintain, and one model can serve several views and controllers.

    Answer : The model is the server-side classes; the view is the HTML page shown by the browser; the controller is the user's actions in the browser – the GET and POST requests.

    Answer : It mixes input handling, validation, SQL and HTML in one file, so the view cannot be replaced, the code is hard to maintain, nothing can be reused, and it even changes data with GET requests.

    Answer : Using PHP itself as the template language: the control page prepares data and then includes a .phtml template that only displays that data using simple PHP.

    Answer : The .php control page should contain no SQL and no HTML; .phpm classes no HTML; .phtml templates no SQL and only basic PHP.

    Answer : A single associative array built by the control page that contains all unformatted data to be displayed, which the view then renders.

    Answer : Apache may not execute them as PHP, so a visitor requesting them directly could download and read the source code.

    Answer : Laravel, Symfony and CodeIgniter (also CakePHP and Yii).
    MCQ Answer Key
    No.QuestionCorrect Answer
    1In MVC, the component that contains business logic and database access is the:C. Model
    2Which component renders output for the user?B. View
    3In the convention described, which file type should contain no SQL?A. .phtml
    4A major benefit of MVC is:B. Interchangeable components
    5MVC is considered an evolution of:B. IPO (Input, Processing, Output)
    Ch-20 : Errors & Exceptions : Error and Exception Handling

    Read the notes, run the programs & take the MCQ test »

    Answer : It sends a message containing the error type, a description, the file name and the line number to the browser (when display_errors is on) and/or to the error log.

    Answer : Without it applications look unprofessional, may stop in an uncontrolled way, and error messages can reveal internal details such as file paths that help attackers.

    Answer : die("message") (an alias of exit) prints a message and stops the script; used after testing a condition such as !file_exists($f), it avoids raw PHP warnings.

    Answer : At least two – the error level and the error message – and optionally the file name and the line number (four in PHP 8; the old fifth error_context parameter is no longer passed).

    Answer : It makes a user-defined function the error handler for the rest of the script, optionally only for the error levels given in the second parameter.

    Answer : E_USER_ERROR (256, fatal), E_USER_WARNING (512, non-fatal) and E_USER_NOTICE (1024, the default).

    Answer : It was raised from a notice (E_NOTICE, 8) to a warning (E_WARNING, 2).

    Answer : display_errors = Off so visitors see no internal details, and log_errors = On with error_log pointing to a log file, with error_reporting = E_ALL.

    Answer : With error_log($message, 1, "admin@example.com", "From: webmaster@example.com"); – message type 1 sends an e-mail.

    Answer : An object representing an exceptional condition that changes the normal flow of the script: when thrown, execution jumps to the nearest matching catch block.

    Answer : try encloses code that may throw; throw raises an exception object; catch receives and handles a matching exception; finally contains code that always runs afterwards.

    Answer : Define a class that extends Exception, optionally adding methods: class customException extends Exception { public function errorMessage() { … } }

    Answer : Throwing a new (often user-friendly) exception from inside a catch block, so that a higher-level handler deals with it.

    Answer : It registers a function that is called for any exception that is not caught by a try/catch block.

    Answer : The interface implemented by both Exception and Error in PHP 7+; catching Throwable catches all exceptions and engine errors such as TypeError and DivisionByZeroError.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which function installs a user-defined error handler?B. set_error_handler()
    2The default level of trigger_error() is:C. E_USER_NOTICE
    3Which block always executes after try/catch?B. finally
    4A custom exception class must:B. Extend Exception
    5In PHP 8, both Exception and Error implement:A. Throwable
    Ch-21 : Filters : PHP Filters

    Read the notes, run the programs & take the MCQ test »

    Answer : A function of the filter extension used to validate (check) or sanitize (clean) data from insecure sources such as forms, cookies and web services.

    Answer : Because it can be wrong or malicious; filtering ensures the application receives data of the correct type and format, which is one of the most important security measures.

    Answer : Form input, cookies, web services data, server variables and database query results.

    Answer : filter_var() filters any variable or value you pass; filter_input() reads a variable directly from an input source (INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV) and filters it.

    Answer : It checks whether a variable of the specified input type exists, e.g. filter_has_var(INPUT_GET, "email").

    Answer : Validating filters check data against strict format rules and return the value (converted to the right type) or false; sanitizing filters remove or encode unwanted characters and always return a string.

    Answer : Additional settings for a filter. Options, given in an array named "options", set values like min_range and max_range; flags, such as FILTER_FLAG_NO_PRIV_RANGE, modify the filter's behaviour.

    Answer : filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1, "max_range" => 120]]) and compare the result with false.

    Answer : Because the valid value 0 is falsy, so if (!filter_var(…)) would wrongly treat 0 as invalid.

    Answer : It removes all characters that are not allowed in a URL, such as spaces and non-ASCII letters.

    Answer : It gets several input variables of one type and filters each with its own filter, flags and options in a single call, returning an array of results.

    Answer : It must be associative with input names as keys, and each value must be a filter ID or an array giving "filter", "flags" and "options".

    Answer : A filter that calls a user-defined or built-in function, named in the "options" element, to filter the value – giving full control over the filtering.

    Answer : FILTER_SANITIZE_MAGIC_QUOTES was removed in 8.0 (use FILTER_SANITIZE_ADD_SLASHES), and FILTER_SANITIZE_STRING/FILTER_SANITIZE_STRIPPED were deprecated in 8.1 (use htmlspecialchars() or FILTER_SANITIZE_FULL_SPECIAL_CHARS).

    Answer : filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE).
    MCQ Answer Key
    No.QuestionCorrect Answer
    1A validating filter returns what when the data is invalid?B. false
    2Which constant reads a variable from the query string in filter_input()?B. INPUT_GET
    3Range limits for FILTER_VALIDATE_INT are given in an array named:C. "options"
    4Which filter calls a user-defined function?A. FILTER_CALLBACK
    5Which filter is deprecated in PHP 8.1?C. FILTER_SANITIZE_STRING
    Ch-22 : .htaccess Security : .htaccess Security

    Read the notes, run the programs & take the MCQ test »

    Answer : A directory-level configuration file for Apache that overrides part of the server's global configuration for its folder and all sub-folders.

    Answer : On Unix-like systems files beginning with a dot are hidden by convention, and Apache is configured to refuse to serve files starting with .ht.

    Answer : No. For performance and security reasons its directives apply only to the current directory and its sub-directories.

    Answer : In httpd.conf it decides which kinds of directives .htaccess files may contain: None ignores them, AuthConfig allows authentication directives, All allows all permitted directives.

    Answer : No. Apache reads .htaccess on every request, so changes take effect immediately (only httpd.conf changes need a restart).

    Answer : A password file created with htpasswd (user:encrypted-password lines) and an .htaccess file in the protected folder with AuthType, AuthName, AuthUserFile and Require.

    Answer : AuthType Basic selects HTTP Basic authentication; AuthName is the realm text shown in the login box; AuthUserFile is the full path of the password file; Require valid-user admits any user in that file.

    Answer : In the XAMPP Shell run C:\xampp\apache\bin\htpasswd.exe -c path\to\.htpasswd username and type the password twice; omit -c to add more users.

    Answer : So that it can never be requested and downloaded through the web server.

    Answer : Because the browser sends the user name and password only Base64-encoded in every request; without HTTPS they can be intercepted and decoded.

    Answer : 401 Unauthorized.

    Answer : <FilesMatch "\.(sql|log)$"> Require all denied </FilesMatch> in .htaccess – Apache then answers 403 Forbidden.

    Answer : It disables automatic directory listings, so a folder without an index file returns 403 Forbidden instead of a list of its files.

    Answer : With ErrorDocument 404 /path/notfound.php in .htaccess.

    Answer : When the requested path is "product/" followed by digits, Apache internally runs product.php with id set to those digits ($1 is the captured group); L makes it the last rule processed.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which directive in httpd.conf must allow .htaccess files to be used?B. AllowOverride
    2Which program creates Apache password files?B. htpasswd
    3Require valid-user allows:C. Any user listed in the AuthUserFile
    4Options -Indexes prevents:B. Directory listings
    5Which module provides RewriteRule?C. mod_rewrite
    Ch-23 : Apache & Array Functions : Apache and Array Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : Only when PHP runs as an Apache module (mod_php), as in XAMPP. They are not available with the CLI, FastCGI/PHP-FPM or the built-in server.

    Answer : An associative array of all HTTP request headers sent by the browser, such as Host, User-Agent and Accept-Language. getallheaders() is an alias.

    Answer : array_combine() builds one array using the first array as keys and the second as values; array_merge() joins several arrays into one.

    Answer : compact("city", "state") creates an array from variables, using their names as keys; extract() does the reverse – it creates variables from array keys.

    Answer : An associative array where each distinct value of the input is a key and the number of its occurrences is the value.

    Answer : array_push() adds elements to the end of an array; array_unshift() adds them to the beginning. Both return the new number of elements.

    Answer : array_pop() removes and returns the last element; array_shift() removes and returns the first element (re-indexing numeric keys).

    Answer : For string keys, the value from the later array overwrites the earlier one; numeric keys are appended and re-numbered.

    Answer : array_slice() returns a portion of an array without changing it; array_splice() removes a portion from the original array and can insert replacement elements.

    Answer : array_diff() returns values of the first array not present in the others; array_intersect() returns values of the first array present in all the others.

    Answer : Keys are compared as well as values, so an element is different if either its key or its value differs.

    Answer : array_map() transforms every element with a callback; array_filter() keeps only elements for which the callback returns true; array_reduce() combines all elements into one value.

    Answer : Sorting alphanumeric strings the way a human would, so "img2" comes before "img10". natsort() is case-sensitive, natcasesort() case-insensitive.

    Answer : next(), prev(), reset() and end(); current() (pos()) and key() read the element at the pointer.

    Answer : each(), which returned the current key/value pair and advanced the pointer. Use a foreach loop instead.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which function adds elements to the beginning of an array?B. array_unshift()
    2array_diff([1,2,3], [2,3,4]) returns:A. [1]
    3Which function keeps key/value pairs while sorting by value in descending order?C. arsort()
    4Which function returns one column of a two-dimensional array?A. array_column()
    5Which array function no longer exists in PHP 8?B. each()
    Ch-24 : Date / Time Functions : Date, Time and Calendar Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : The number of seconds that have elapsed since 1 January 1970 00:00:00 GMT (the Unix Epoch). time() returns the current timestamp.

    Answer : In php.ini set date.timezone = Asia/Kolkata, or call date_default_timezone_set("Asia/Kolkata") at the start of the script.

    Answer : date(format [, timestamp]) – it returns the timestamp (default: now) formatted according to the format string.

    Answer : date("d-m-Y h:i A").

    Answer : d is the day with a leading zero (01–31), j without (1–31). h is the 12-hour hour with a leading zero (01–12), H the 24-hour hour with a leading zero (00–23).

    Answer : l (lowercase L) gives the full day name, e.g. Thursday; F gives the full month name, e.g. October.

    Answer : Escape it with a backslash, e.g. date("\T\o\d\a\y \i\s l").

    Answer : It returns the Unix timestamp for the given hour, minute, second, month, day and year; omitted arguments take the current values.

    Answer : checkdate(2, 29, 2027) – it returns false because 2027 is not a leap year.

    Answer : It converts an English date/time description into a timestamp, e.g. strtotime("next monday") or strtotime("+1 week", $base).

    Answer : Create two DateTime objects and call $d1->diff($d2); the returned DateInterval has y, m, d and days properties.

    Answer : $d = new DateTime("2026-10-22"); $d->modify("+45 days"); or $d->add(new DateInterval("P45D"));

    Answer : A continuous count of days since 1 January 4713 BC, used by the calendar functions to convert between Gregorian, Julian, Jewish and French Republican dates.

    Answer : cal_days_in_month(CAL_GREGORIAN, $month, $year), or date("t", $timestamp).

    Answer : strftime() and gmstrftime(). Use date()/DateTime::format() or the IntlDateFormatter class for locale-aware formatting.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which format character prints the full name of the day?C. l
    2date("H") returns the hour in:B. 24-hour format with leading zero
    3Which function validates a date?B. checkdate()
    4The Unix Epoch is:B. 1 January 1970 GMT
    5Which function is deprecated since PHP 8.1?C. strftime()
    Ch-25 : Class, Directory & File Functions : Class/Object, Function Handling, Directory and File Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : With class_exists("ClassName"), which returns true or false (and may trigger the autoloader).

    Answer : get_class_vars() returns the default properties of a class; get_object_vars() returns the current accessible properties and values of a particular object.

    Answer : An array with the names of the methods of a class (those accessible from the calling scope), including inherited ones.

    Answer : is_a() is true if the object belongs to the class or has it as a parent; is_subclass_of() is true only if the class is a parent, not for the object's own class.

    Answer : To call a function when its arguments are available as an array: call_user_func_array('welcome', ['Ravi', 'Bhopal']).

    Answer : func_num_args() (count), func_get_arg(n) (one argument) and func_get_args() (all arguments). Modern code uses ...$args.

    Answer : It registers a function that PHP executes when the script finishes, normally or after exit(), useful for logging and clean-up.

    Answer : It was deprecated in 7.2 and removed in 8.0 because it used eval() internally; anonymous functions (function () {} or fn) replace it.

    Answer : mkdir("a/b/c", 0777, true) – the third argument true creates missing parent directories.

    Answer : scandir($dir) lists all entries (including . and ..) of one directory; glob($pattern) returns paths that match a wildcard pattern such as *.txt.

    Answer : $h = opendir($dir); while (($e = readdir($h)) !== false) { … } closedir($h); – skipping the entries "." and "..".

    Answer : rmdir($dir); the directory must be empty, so its files must be deleted first with unlink().

    Answer : Open it with fopen() and call fgetcsv($handle) in a loop; each call returns one line as an array of fields.

    Answer : basename() the file name part of a path, dirname() the directory part, and pathinfo() an array (or one part) with dirname, basename, extension and filename.

    Answer : It places a shared (LOCK_SH) or exclusive (LOCK_EX) lock on a file and releases it with LOCK_UN, preventing two requests from writing the same file at the same time.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which function returns the name of an object's class?A. get_class()
    2Which function was removed in PHP 8.0?B. create_function()
    3Which function lists files matching *.txt?B. glob()
    4rmdir() succeeds only if the directory is:B. Empty
    5Which function parses a line of a CSV file into an array?B. fgetcsv()
    Ch-26 : Error, HTTP, Mail & Math Functions : Error, HTTP, Mail and Mathematical Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : It sets or returns the level of errors PHP reports for the current script, e.g. error_reporting(E_ALL) or error_reporting(E_ALL & ~E_NOTICE).

    Answer : 0 sends the message to PHP's system logger/log file, 1 sends it by e-mail to the destination address, 3 appends it to the destination file, 4 sends it to the SAPI logging handler.

    Answer : The list of function calls that led to the current point in the program; debug_backtrace() returns it as an array and debug_print_backtrace() prints it.

    Answer : An associative array (type, message, file, line) describing the last error that occurred, or null if none.

    Answer : header("Location: page.php"); followed by exit; so that the rest of the script does not run.

    Answer : HTTP headers are sent before the page body; once any output (even a space) has been sent, the headers are already gone and PHP reports "headers already sent".

    Answer : headers_list() returns the headers that are prepared to be sent; headers_sent() tells whether the headers have already been sent (and where output started).

    Answer : setcookie() URL-encodes the cookie value automatically; setrawcookie() sends the value as it is.

    Answer : ceil() rounds up to the next integer, floor() rounds down, and round() rounds to the nearest value with an optional number of decimal places.

    Answer : intdiv(a, b) returns the integer quotient; fmod(x, y) returns the floating-point remainder.

    Answer : In radians; convert degrees with deg2rad() (and back with rad2deg()).

    Answer : dechex(255) gives "ff" and decbin(255) gives "11111111".

    Answer : number_format(1234567.891, 2) gives 1,234,567.89 (Western grouping); Indian grouping (12,34,567.89) needs the NumberFormatter class with the en_IN locale.

    Answer : mt_rand() is fast but predictable (pseudo-random) and can be seeded; random_int() is cryptographically secure and should be used for OTPs, tokens and passwords.

    Answer : To make the random sequence repeatable, for example in tests or demonstrations.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which function rounds 4.1 up to 5?C. ceil()
    2header("Location: home.php"); is used to:B. Redirect the browser
    3Which error_log() message type appends to a file?C. 3
    4dechex(255) returns:A. "ff"
    5For a secure OTP you should use:C. random_int()
    Ch-27 : MySQL → MySQLi Functions : MySQL Functions and their MySQLi Equivalents

    Read the notes, run the programs & take the MCQ test »

    Answer : The mysql extension was removed in PHP 7.0, so in PHP 8 functions such as mysql_connect() do not exist and calling them causes "Fatal error: Uncaught Error: Call to undefined function".

    Answer : Deprecated in PHP 5.5 and removed in PHP 7.0.

    Answer : It did not support prepared statements (making SQL injection easy) and it did not support newer MySQL features such as multiple statements, transactions API and better SSL/charset handling.

    Answer : MySQL improved. It provides a procedural interface (mysqli_* functions) and an object-oriented interface (the mysqli, mysqli_result and mysqli_stmt classes).

    Answer : mysqli_connect($host, $user, $pass, $db), which can select the database directly, or new mysqli(...) in OOP style; mysqli_select_db($link, $db) / $link->select_db($db) changes it later.

    Answer : In the classic functions the link was an optional last argument; in MySQLi procedural functions the connection is a required first argument, e.g. mysqli_query($link, $sql).

    Answer : mysqli_fetch_array($result) and mysqli_fetch_assoc($result), or $result->fetch_array() and $result->fetch_assoc().

    Answer : mysqli_num_rows($result) or $result->num_rows.

    Answer : mysqli_insert_id($link) or $link->insert_id.

    Answer : mysqli_error($link) / $link->error for the message and mysqli_errno($link) / $link->errno for the number; connection errors use mysqli_connect_error().

    Answer : By running SQL statements: SHOW DATABASES, SHOW TABLES, SHOW COLUMNS FROM table, with mysqli_query() or $link->query().

    Answer : mysql_escape_string() escaped special characters without considering the connection's character set; mysql_real_escape_string() took the charset into account. In MySQLi use mysqli_real_escape_string() – or better, prepared statements.

    Answer : A connection kept open by the web server process and reused by later requests. In MySQLi prefix the host with "p:", e.g. mysqli_connect("p:localhost", …).

    Answer : Move to the row with mysqli_data_seek($result, $row) and read it with mysqli_fetch_row() (or the OOP methods data_seek() and fetch_row()).

    Answer : Prepared statements, which send user input separately from the SQL statement and therefore prevent SQL injection.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1In which PHP version was the mysql extension removed?C. 7.0
    2The MySQLi procedural equivalent of mysql_query($sql) is:B. mysqli_query($link, $sql)
    3$link->insert_id is the OOP equivalent of:B. mysql_insert_id()
    4Which feature of MySQLi prevents SQL injection?B. Prepared statements
    5Running mysql_connect() on PHP 8 gives:B. Fatal error: Call to undefined function
    Ch-28 : Network, Buffer, Config & Session Functions : Network, Output Buffer, Configuration and Session Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : gethostbyname() returns the IPv4 address of a host name; gethostbyaddr() returns the host name of an IP address.

    Answer : They convert IPv4 addresses to integers and back, which makes it easy to store addresses in a database and to compare IP ranges.

    Answer : 80 – the port number of the HTTP service over TCP.

    Answer : To open a raw TCP/UDP or Unix socket connection to a host and port, so that the script can talk to another server directly with fwrite()/fgets().

    Answer : A mechanism in which PHP stores output in a memory buffer instead of sending it immediately, so it can be modified, captured or discarded and headers can still be sent.

    Answer : ob_end_flush() sends the buffer contents to the browser and turns buffering off; ob_end_clean() discards the contents and turns buffering off.

    Answer : ob_start(); include "file.php"; $html = ob_get_clean();

    Answer : It starts buffering and passes the buffered output through the callback function before it is sent, e.g. to compress or modify it (ob_gzhandler compresses).

    Answer : With ini_set("option", "value"); ini_get() reads the current value, and get_cfg_var() still returns the php.ini value.

    Answer : extension_loaded("mysqli") returns true if it is loaded; function_exists("mysqli_connect") also works.

    Answer : "apache2handler", because PHP runs as an Apache module; from the command line it returns "cli".

    Answer : get_magic_quotes_gpc()/get_magic_quotes_runtime() (removed in 8.0) and set_magic_quotes_runtime() (7.0) because magic quotes were removed; restore_include_path() was removed in 8.0; php_logo_guid()/zend_logo_guid() in 5.5.

    Answer : It gives the current session a new id while keeping its data; it should be called after login to prevent session fixation attacks.

    Answer : session_unset() empties all session variables but keeps the session; session_destroy() destroys the session data on the server.

    Answer : The $_SESSION superglobal: $_SESSION['name'] = value; unset($_SESSION['name']) and isset($_SESSION['name']) replace session_register(), session_unregister() and session_is_registered().
    MCQ Answer Key
    No.QuestionCorrect Answer
    1ip2long("192.168.1.10") returns:B. An integer
    2Which function returns the buffer contents and deletes the buffer?B. ob_get_clean()
    3Which function changes a php.ini setting for the current script only?B. ini_set()
    4What does php_sapi_name() return under XAMPP's Apache?B. apache2handler
    5Which session function was removed in PHP 5.4?B. session_register()
    Ch-29 : String & Variable Functions : String, Variable and Miscellaneous Functions

    Read the notes, run the programs & take the MCQ test »

    Answer : strlen() returns the number of bytes (characters) in a string; str_word_count() returns the number of words.

    Answer : Both return the position of the first occurrence of a substring; strpos() is case-sensitive, stripos() is case-insensitive.

    Answer : Because the substring may be found at position 0, which is falsy; comparing with != false or using it directly in if would wrongly treat a match at the start as "not found".

    Answer : str_replace() replaces every occurrence of a search string; substr_replace() replaces the part of a string starting at a given position and length.

    Answer : explode(",", $s) splits a string into an array at each separator; implode(",", $a) joins array elements into a string with the glue.

    Answer : printf() outputs the formatted string directly; sprintf() returns it so that it can be stored or processed further.

    Answer : A negative number if the first string is less than the second, 0 if they are equal, and a positive number if it is greater (case-sensitive).

    Answer : They measure how alike two strings are – levenshtein() counts the edits needed to turn one into the other, similar_text() returns the number of matching characters and a percentage – useful for "did you mean" suggestions.

    Answer : htmlspecialchars() converts special characters into entities so tags are displayed as text; strip_tags() removes the tags completely.

    Answer : MD5 (and SHA-1) are fast and unsalted, so passwords can be cracked by brute force or rainbow tables. Use password_hash() to store and password_verify() to check passwords.

    Answer : The POSIX regular-expression functions ereg(), eregi(), ereg_replace(), eregi_replace(), split(), spliti() and sql_regcase(); use the preg_* functions instead.

    Answer : isset() is true if the variable exists and is not null; empty() is true if the variable does not exist or has an "empty" value such as "", 0, "0", null, false or an empty array.

    Answer : Converting a PHP value (e.g. an array or object) into a storable string with serialize(), and restoring it later with unserialize().

    Answer : print_r() prints a readable structure; var_dump() also shows types and lengths; var_export() outputs valid PHP code that recreates the value.

    Answer : A unique identifier based on the current time in microseconds (13 hex characters, optionally with a prefix and extra entropy); it is used for file names, order numbers and similar ids – not for security tokens.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which function splits a string into an array by a separator?B. explode()
    2strcmp("apple", "apple") returns:C. 0
    3Which function should be used to store a password?C. password_hash()
    4Which function was removed in PHP 7.0?C. split()
    5empty("0") returns:A. true
    Ch-30 : Cookies & Query Strings : State Management – Cookies and Query Strings

    Read the notes, run the programs & take the MCQ test »

    Answer : Because each HTTP request is independent; the server does not remember earlier requests, so it cannot tell by itself whether requests come from the same client.

    Answer : The techniques used to preserve information about a user or page across multiple HTTP requests, such as cookies, query strings, sessions and databases.

    Answer : Client-side: cookies, query strings and hidden form fields. Server-side: session state and database support.

    Answer : Advantage: less load on the server, so better performance. Disadvantage: only a limited amount of data can be stored, and the user can see and change it.

    Answer : A small piece of text data that a server sends to the browser, which stores it and sends it back with every later request to the same site.

    Answer : A temporary (session) cookie has no expiry time and is deleted when the browser is closed; a persistent cookie has an expiry time and is stored on the client until then.

    Answer : setcookie(name, value, expire, path, domain, secure, httponly): name and value of the cookie, expiry timestamp, path and domain where it is valid, secure to send only over HTTPS, httponly to hide it from JavaScript.

    Answer : Cookies are sent in the HTTP headers, which must be sent before the page body; after output has started PHP cannot add headers.

    Answer : Through the superglobal $_COOKIE, e.g. $_COOKIE['cookie1'], starting from the next request after it was set.

    Answer : By calling setcookie() with the same name (and path) and an expiry time in the past, e.g. setcookie("cookie2", "", time() - 3600).

    Answer : Limited size (about 4096 bytes per cookie), users can disable them, and users can read and tamper with them because they are stored on the client.

    Answer : The part of a URL after the ? character, consisting of name=value pairs separated by &, used to pass data from one page to another, e.g. page2.php?d1=23&d2=45.

    Answer : With $_GET['name'] (or $_REQUEST). Values must be encoded with urlencode() or http_build_query() so that characters like &, = and spaces do not break the URL.

    Answer : The data is visible in the address bar, history and logs, it can easily be changed by the user, and the length of URLs is limited.

    Answer : An <input type="hidden"> element whose value is sent with the form but not displayed; it can still be seen in the page source and modified, so it must be validated.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1HTTP is a ______ protocol.B. stateless
    2Which of these is a server-side state management option?C. Session
    3How do you create a cookie that expires in one hour?B. setcookie("c", "v", time() + 3600)
    4Most browsers limit a single cookie to about:B. 4096 bytes
    5In page2.php?d1=23&d2=45, the value of d2 is read with:C. $_GET['d2']
    Ch-31 : Sessions : State Management – Sessions

    Read the notes, run the programs & take the MCQ test »

    Answer : A mechanism for storing user-specific data on the server across multiple page requests, identified by a unique session id stored in a cookie on the client.

    Answer : Cookies store data on the client, are limited to about 4 KB and can be read and changed by the user; sessions store data on the server, can hold much more, and send only a random id to the client, so they are more secure.

    Answer : It creates a new session with a random id (sending the PHPSESSID cookie) or resumes the existing session identified by the cookie, and loads its data into $_SESSION.

    Answer : Because it may send a cookie in the HTTP headers, and headers cannot be sent after output has started.

    Answer : The default name of the cookie that stores the session id on the client; it can be changed with session.name or session_name().

    Answer : In files named sess_<id> in the folder given by session.save_path, by default C:\xampp\tmp.

    Answer : Store: $_SESSION['views'] = 1; read: echo $_SESSION['views']; on any page after session_start().

    Answer : The $_SESSION array replaced it. session_register() depended on register_globals and was removed in PHP 5.4.

    Answer : session_start(); if (isset($_SESSION['views'])) $_SESSION['views']++; else $_SESSION['views'] = 1; echo "Views=" . $_SESSION['views'];

    Answer : unset() removes one session variable; session_unset() removes all session variables but keeps the session; session_destroy() deletes the whole session data on the server.

    Answer : At the top of the page: session_start(); if (!isset($_SESSION['user'])) { header("Location: login.php"); exit; }

    Answer : session_encode() returns all current session variables as one encoded string; session_decode() takes such a string and recreates the session variables in the current session.

    Answer : When session_destroy() is called (e.g. at logout), when the browser is closed (the session cookie is deleted), or when the data is removed by garbage collection after session.gc_maxlifetime seconds of inactivity.

    Answer : Advantages: data is kept securely on the server and can be large and complex. Disadvantages: it uses server resources until it expires, and it lasts only for the browser session.

    Answer : To give the user a new session id, so that an attacker who knew or planted the old id (session fixation) cannot use it to take over the logged-in session.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Where is session data stored?B. On the server
    2The default name of the session cookie is:B. PHPSESSID
    3Which superglobal stores session variables?B. $_SESSION
    4Which function deletes all session data on the server?C. session_destroy()
    5Which function was removed in PHP 5.4?C. session_register()
    Ch-32 : MySQL Fundamentals : Database Support and MySQL Fundamentals

    Read the notes, run the programs & take the MCQ test »

    Answer : To store large amounts of user-specific data permanently – data that must survive server restarts and be available across sessions – such as user accounts, preferences, carts and orders.

    Answer : Security (login credentials and rights are checked against the database), consistency (transactions, referential integrity and triggers) and personalisation (user preferences can be stored and looked up quickly).

    Answer : An open source relational database management system that uses SQL, developed and supported by Oracle Corporation and written in C and C++.

    Answer : Data is stored in separate tables that are related to each other through common fields (keys), instead of one big store, which gives speed and flexibility.

    Answer : Structured Query Language – the standard language (defined by ANSI/ISO) used to create, query and modify relational databases.

    Answer : MySQL is named after My, the daughter of co-founder Monty Widenius. MariaDB is a community fork of MySQL started by Widenius in 2009 (named after his daughter Maria); it is a drop-in replacement and is installed by XAMPP.

    Answer : CHAR(n) always stores n characters, padding shorter values; VARCHAR(n) stores only the actual characters (up to n) plus a length byte, saving space for values of varying length.

    Answer : DECIMAL(length, decimals), e.g. DECIMAL(8,2), because it stores exact values; FLOAT/DOUBLE are approximate and can cause rounding errors.

    Answer : A primary key uniquely identifies each row of a table; a foreign key is a column in another table that refers to that primary key, linking the two tables.

    Answer : Transaction-safe tables (InnoDB) can roll back uncommitted changes and recover after crashes; non-transaction-safe tables (MyISAM, MEMORY) apply every change permanently and immediately, but are lighter.

    Answer : InnoDB supports transactions, row-level locking for many simultaneous users, foreign keys and crash recovery; it has been MySQL's default engine since version 5.5.

    Answer : SELECT lists the fields (or *), AS gives aliases, FROM names the tables, WHERE filters rows, ORDER BY sorts (DESC for descending) and LIMIT offset, count restricts the number of rows returned.

    Answer : 10 rows starting after the first 9, i.e. records 10 to 19 – used for paging.

    Answer : An inner join returns only rows that have matching values in both tables; a LEFT JOIN returns all rows of the left table and fills the columns of the right table with NULL where there is no match.

    Answer : Every row of the table is updated or deleted, so the WHERE clause should always be checked before running such statements.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which storage engine is the default in current MySQL/MariaDB and supports transactions?C. InnoDB
    2Which data type stores exact monetary values?B. DECIMAL
    3Which clause sorts the result of a SELECT?B. ORDER BY
    4WHERE name LIKE 'A%' finds names that:C. Start with A
    5Which statement removes a whole table?B. DROP TABLE table
    Ch-33 : PHP/MySQL (classic API) : PHP and MySQL – The Classic mysql API

    Read the notes, run the programs & take the MCQ test »

    Answer : The host name (localhost in XAMPP), the user name (root by default), the password (empty by default in XAMPP) and the database name.

    Answer : So that they are written once, included wherever needed, easy to change, and kept out of every page – which is safer and easier to maintain.

    Answer : mysql_select_db("database"), equivalent to the SQL command USE database.

    Answer : It sends any SQL statement to the MySQL server and returns a result set for SELECT, or true/false for other statements.

    Answer : With a while loop: while ($row = mysql_fetch_array($result)) { … } – the function returns false when no rows remain.

    Answer : mysql_fetch_array() returns the row with both field-name keys and numeric keys; mysql_fetch_row() returns only a numeric array.

    Answer : If the function fails (returns false), die() stops the script and prints the error message returned by the MySQL server.

    Answer : To escape quotes and special characters in user input before putting it into SQL, to reduce the risk of SQL injection. Prepared statements are the modern, safer solution.

    Answer : The AUTO_INCREMENT id generated by the last INSERT statement.

    Answer : The number of rows changed by the last INSERT, UPDATE or DELETE statement.

    Answer : XAMPP 8 uses PHP 8, from which the mysql extension was removed (in PHP 7.0); calling mysql_connect() gives a fatal "Call to undefined function" error.

    Answer : mysqli_query($connection, $sql) – the connection becomes the first argument.

    Answer : extension=mysqli (enabled by default in XAMPP).

    Answer : Connect to the server, select the database, run a query, fetch and process the results, close the connection.

    Answer : Listing L33.n is Program 34.n in MySQLi procedural style (Chapter 34) and Program 35.n in MySQLi object-oriented style (Chapter 35).
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which classic function is equivalent to the SQL command USE?B. mysql_select_db()
    2Which loop is normally used to read all rows of a result set?C. while ($row = …fetch_array($result))
    3mysql_fetch_array() returns a row as:C. An associative and numeric array
    4The default user name of MySQL/MariaDB in XAMPP is:C. root
    5Classic mysql_* code on XAMPP 8 results in:C. Fatal error: Call to undefined function
    Ch-34 : MySQLi – Procedural : PHP and MySQLi – Procedural Style

    Read the notes, run the programs & take the MCQ test »

    Answer : MySQL improved – PHP's extension for MySQL/MariaDB (since PHP 5), offering both a procedural and an object-oriented interface, with prepared statements, transactions and multiple statements.

    Answer : Function names start with mysqli_ instead of mysql_, and the connection is a required first argument of most functions, e.g. mysqli_query($conn, $sql).

    Answer : $conn = mysqli_connect("localhost", "root", "", "phpbook");

    Answer : It throws a mysqli_sql_exception (because the default report mode is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT), so code after the call – including "or die()" – is not reached unless the exception is caught.

    Answer : Wrap the call in try { … } catch (mysqli_sql_exception $e) { … }, log $e->getMessage() and show a friendly message to the user.

    Answer : So that it is written once and required by all pages; changing the password or host then needs only one edit.

    Answer : A mysqli_result object for statements that return rows (SELECT, SHOW, DESCRIBE), and true for successful INSERT, UPDATE, DELETE, CREATE etc. (false on failure when exceptions are off).

    Answer : fetch_assoc returns a row as an array with column-name keys, fetch_row as a numeric array, and fetch_object as an object whose properties are the column names.

    Answer : It returns all remaining rows of a result as an array of rows (MYSQLI_NUM by default, or MYSQLI_ASSOC/MYSQLI_BOTH).

    Answer : mysqli_num_rows($result) for a SELECT result; mysqli_affected_rows($conn) for INSERT, UPDATE and DELETE.

    Answer : With mysqli_insert_id($conn) immediately after the INSERT.

    Answer : It escapes quotes and other special characters in a string so that it can be placed safely inside an SQL string literal, e.g. the apostrophe in O'Brien.

    Answer : It executes several SQL statements separated by semicolons in one call; if user input reaches it, an attacker can append harmful statements, so it must never be used with user input.

    Answer : Create, Read, Update and Delete – the four basic operations on data, implemented with INSERT, SELECT, UPDATE and DELETE.

    Answer : Casting to integer guarantees that only a number is placed in the SQL statement, so text such as "1 OR 1=1" cannot change the query.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1In the procedural style, the connection is passed to mysqli_query() as the:B. First argument
    2Since PHP 8.1, a failed MySQLi query by default:C. Throws mysqli_sql_exception
    3Which function returns all rows of a result at once?B. mysqli_fetch_all()
    4Which function gives the number of rows changed by UPDATE?B. mysqli_affected_rows()
    5Which fetch function lets you write $row->name?C. mysqli_fetch_object()
    Ch-35 : MySQLi – Object Oriented : PHP and MySQLi – Object-Oriented Style

    Read the notes, run the programs & take the MCQ test »

    Answer : mysqli (the connection), mysqli_result (a query result set) and mysqli_stmt (a prepared statement).

    Answer : $conn = new mysqli("localhost", "root", "", "phpbook"); – the constructor takes host, user, password, database (and optionally port and socket).

    Answer : In PHP 8.1+ catch the mysqli_sql_exception thrown by new mysqli(); with exceptions switched off, test $conn->connect_error (message) and $conn->connect_errno (number).

    Answer : $result = $conn->query($sql); and $row = $result->fetch_assoc();

    Answer : Calling a method on the object returned by another method in one expression, e.g. $row = $conn->query($sql)->fetch_assoc();

    Answer : $result->num_rows for a SELECT result; $conn->affected_rows for INSERT, UPDATE and DELETE.

    Answer : $conn->insert_id.

    Answer : mysqli_result is traversable, so foreach ($result as $row) { … } gives each row as an associative array.

    Answer : It fetches the next row and returns it as an object of the class Course, with the columns as properties, so the class's methods can be used on the row.

    Answer : The error message and error number of the most recent statement on that connection (useful when exceptions are switched off).

    Answer : Duplicate entry – an INSERT or UPDATE tried to store a value that already exists in a UNIQUE or PRIMARY KEY column.

    Answer : To keep connection details and common operations in one place, reuse them everywhere, change the database code without touching pages, and (with a singleton) share one connection.

    Answer : $result->free(); and $conn->close();

    Answer : It contains all SQL for the students table (all, find, save, delete), so the page only calls methods and displays results – a simple separation of data access from presentation.

    Answer : Both have the same features and performance. Procedural is closer to old mysql_* code and easy to convert; OOP fits object-oriented applications, frameworks and classes better. Use one style consistently within a project.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which statement creates a MySQLi connection object?B. new mysqli(...)
    2In OOP style, the number of rows in a SELECT result is:B. $result->num_rows
    3$conn->insert_id returns:B. The AUTO_INCREMENT id of the last INSERT
    4Which loop can iterate a mysqli_result directly?B. foreach
    5MySQL error 1062 means:C. Duplicate entry
    Ch-36 : Prepared Statements : MySQLi Prepared Statements, Transactions and Security

    Read the notes, run the programs & take the MCQ test »

    Answer : An attack in which input supplied by a user is inserted into an SQL statement in such a way that it changes the statement's meaning, allowing the attacker to bypass logins or read, change or delete data.

    Answer : The first quote closes the password string, and OR '1'='1' adds a condition that is always true, so the WHERE clause matches rows even though the password is wrong.

    Answer : An SQL statement with ? placeholders that is sent to the server first and executed later with values sent separately, so the values can never be interpreted as SQL code.

    Answer : Prepare the SQL with placeholders, bind the variables (with their types), and execute; for SELECT then fetch the results.

    Answer : i = integer, d = double (float), s = string, b = blob (binary data); the type string contains one letter per placeholder.

    Answer : $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, "si", $a, $b); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt);

    Answer : $stmt = $conn->prepare($sql); $stmt->bind_param("si", $a, $b); $stmt->execute(); $result = $stmt->get_result();

    Answer : get_result() returns a mysqli_result object that can be fetched as arrays or objects; bind_result() binds each result column to a variable, and fetch() fills those variables row by row.

    Answer : PHP 8.1 lets execute() receive the values as an array (no bind_param needed); PHP 8.2 added mysqli_execute_query() / $conn->execute_query(), which prepares, binds and executes in one call.

    Answer : No – placeholders are only for values. Table/column names or sort directions from user input must be checked against a whitelist of allowed values.

    Answer : A group of SQL statements executed as one unit: either all of them are made permanent with commit, or all are undone with rollback.

    Answer : Atomicity (all or nothing), Consistency (data stays valid), Isolation (concurrent transactions do not interfere) and Durability (committed data survives crashes).

    Answer : begin_transaction(), commit() and rollback() (procedural: mysqli_begin_transaction(), mysqli_commit(), mysqli_rollback()); autocommit(false) also starts manual transaction mode.

    Answer : password_hash() uses a slow, salted algorithm (bcrypt/Argon2) designed for passwords, so each hash is unique and brute-force attacks are very slow; md5() is fast, unsalted and easily cracked.

    Answer : Fetch the stored hash for the user name with a prepared statement and call password_verify($typedPassword, $storedHash), which returns true if they match.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Prepared statements protect against:B. SQL injection
    2In bind_param("sid", $a, $b, $c), $b is bound as:B. An integer
    3Which PHP 8.2 method prepares, binds and executes in one call?B. $conn->execute_query()
    4Which method undoes all statements of the current transaction?B. rollback()
    5Which function checks a password against a stored hash?C. password_verify()
    Ch-37 : ODBC : Database Support using ODBC

    Read the notes, run the programs & take the MCQ test »

    Answer : Open Database Connectivity – a standard API through which an application can access many different database systems using database-specific drivers loaded by an ODBC driver manager.

    Answer : A Data Source Name – a named configuration that tells the ODBC driver manager which driver to use and where the database is (file, server, database name, options).

    Answer : A User DSN is visible only to the Windows user who created it; a System DSN is visible to all users and to services such as Apache, so PHP applications normally need a System DSN.

    Answer : Open ODBC Data Sources (Administrative Tools), choose the System DSN tab, click Add, select the Microsoft Access Driver and click Finish, click Select to locate the database, give a DSN name and click OK.

    Answer : Remove the semicolon before extension=odbc in C:\xampp\php\php.ini and restart Apache.

    Answer : The data source name, the user name, the password and an optional cursor type; it returns a connection resource or false.

    Answer : It executes an SQL statement on an ODBC connection and returns a result identifier (or false on error).

    Answer : true if it could move to the next row of the result, false when there are no more rows; it takes the result identifier and an optional row number.

    Answer : odbc_result($rs, 1) reads the first field of the current row; odbc_result($rs, "CompanyName") reads the field by name.

    Answer : while (odbc_fetch_row($rs)) { $name = odbc_result($rs, "CompanyName"); echo $name . "<br>"; }

    Answer : With odbc_close($conn), or odbc_close_all() for all connections.

    Answer : $stmt = odbc_prepare($conn, "SELECT … WHERE Country = ?"); odbc_execute($stmt, [$country]); then fetch rows from $stmt.

    Answer : odbc_error($conn) returns the SQLSTATE code, and odbc_errormsg($conn) returns the error message of the last failed operation.

    Answer : A 64-bit PHP process can only load 64-bit ODBC drivers (and 32-bit only 32-bit drivers); a mismatch results in "data source name not found" errors.

    Answer : When the database has no native PHP extension or must be accessed through an existing ODBC setup – for example an MS Access file or a legacy database. For MySQL/MariaDB, MySQLi is preferred.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1ODBC stands for:B. Open Database Connectivity
    2Which DSN type is visible to Apache running as a service?C. System DSN
    3Which function moves to the next row of an ODBC result?B. odbc_fetch_row()
    4odbc_result($rs, "CompanyName") returns:B. The value of the CompanyName field of the current row
    5Which php.ini line enables ODBC?A. extension=odbc
    Ch-38 : XML : XML with PHP

    Read the notes, run the programs & take the MCQ test »

    Answer : eXtensible Markup Language – a W3C markup language for storing and exchanging self-describing data using tags defined by the author.

    Answer : Because it has no fixed set of tags; authors define their own tags to describe their data.

    Answer : One application converts its data to XML, which any other platform can read and convert into its own structures, so very different systems can exchange data through a common, standard format.

    Answer : RSS/Atom feeds and sitemaps, web services (SOAP), office document formats (.docx, .xlsx), configuration files, SVG graphics and VoiceXML (any four).

    Answer : The optional declaration <?xml version="1.0" encoding="UTF-8"?> on the first line that states the XML version and character encoding.

    Answer : A single tag for an element without content, written with a slash before the closing bracket, e.g. <photo src="a.jpg" />.

    Answer : Tags must be closed in the reverse order in which they were opened – an element opened inside another must be closed before the outer element is closed.

    Answer : One root element; every element closed; correct nesting; case-sensitive matching tags; quoted attribute values; special characters escaped as entities; the prolog, if present, comes first.

    Answer : An element is a tag pair with its content and children, e.g. <name>Danish</name>; an attribute is a name="value" pair inside an opening tag that gives extra information, e.g. <friend age="23">.

    Answer : If element A is contained (directly or indirectly) by B, A is a descendant of B and B is an ancestor of A; the root element is the ancestor of all other elements.

    Answer : A PHP extension that converts an XML document into an object, so that elements are reached as properties ($xml->book[0]->title) and attributes like array keys ($book['id']).

    Answer : $xml = simplexml_load_file("note.xml"); foreach ($xml->children() as $child) { echo $child->getName() . ": " . $child; }

    Answer : The W3C Document Object Model – a standard, language-independent set of objects and methods for accessing and changing HTML and XML documents as a tree of nodes.

    Answer : A tree-based parser (DOM, SimpleXML) loads the whole document into memory as a tree; an event-based parser (Expat, XMLReader) reads the document sequentially and calls handlers for each start tag, text and end tag, using little memory.

    Answer : The white space (new lines and indentation) between elements is stored as text nodes. Set preserveWhiteSpace = false before loading or skip nodes that are not XML_ELEMENT_NODE.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1XML tags are:B. Defined by the author
    2Which document is NOT well-formed?B. <a><b>x</a></b>
    3Which PHP function loads an XML file into a SimpleXMLElement?B. simplexml_load_file()
    4In SimpleXML, the attribute id of $book is read as:B. $book['id']
    5The DOM parser is a:B. Tree-based parser
    Ch-39 : AJAX : PHP and AJAX

    Read the notes, run the programs & take the MCQ test »

    Answer : Asynchronous JavaScript And XML – a technique that uses JavaScript, the DOM, XMLHttpRequest and XML/JSON to exchange data with the server in the background and update parts of a page without reloading it.

    Answer : Jesse James Garrett of Adaptive Path, in 2005.

    Answer : The JavaScript layer loaded with the page that sits between the user interface and the server; it sends requests asynchronously, handles some processing itself and updates the page.

    Answer : In the classic model each action loads a whole new page and the user waits; in the AJAX model only data is requested in the background, the user keeps working, and only the changed part of the page is updated.

    Answer : A JavaScript object (originally an ActiveX control in IE5) used to send HTTP requests to the server and receive the responses as text or XML without reloading the page.

    Answer : In a synchronous request (open(..., false)) the script waits until the response arrives, freezing the page; in an asynchronous request (open(..., true)) the script continues and a handler is called when the response is ready.

    Answer : 0 uninitialized, 1 open (open() called), 2 sent (send() called), 3 receiving (part of the response received), 4 complete (whole response received).

    Answer : responseText returns the response as a string; responseXML returns it as a parsed XML document object (only if the response is XML), which can be read with DOM methods.

    Answer : The HTTP status code of the response, e.g. 200 for OK or 404 for Not Found; statusText contains the matching text.

    Answer : open(method, url, async, user, password): the HTTP method (GET, POST …), the URL of the server script, true for asynchronous or false for synchronous, and an optional user name and password.

    Answer : To tell the server the format of the data sent with send(), e.g. setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); it must be called after open() and before send().

    Answer : IFrames loaded another page into part of the current page without a full reload. XMLHttpRequest transfers only data and lets JavaScript control exactly how and where it is displayed.

    Answer : JavaScript Object Notation – a lightweight text format of objects {}, arrays [] and values. It is smaller than XML and can be turned into JavaScript objects directly with JSON.parse(), which keeps client code simple.

    Answer : json_encode() converts arrays/objects to a JSON string; json_decode() converts JSON into a PHP object (or an associative array with the second argument true). json_last_error_msg() reports errors.

    Answer : A modern, promise-based JavaScript API for HTTP requests – a simpler replacement for XMLHttpRequest, e.g. const data = await (await fetch(url)).json();
    MCQ Answer Key
    No.QuestionCorrect Answer
    1Which readyState value means the response is complete?D. 4
    2The third argument of xhr.open("GET", url, true) makes the request:C. Asynchronous
    3Which property returns the server response as a string?B. responseText
    4Which PHP function turns an array into JSON?C. json_encode()
    5AJAX was originally made possible by an object first shipped in:B. Internet Explorer 5
    Ch-40 : CMS Concepts : Content Management System (CMS) – Concepts

    Read the notes, run the programs & take the MCQ test »

    Answer : Visitors return to sites that have new information – news, weather, posts – so frequently updated content keeps users coming back and keeps the site alive.

    Answer : Keeping the information (articles, images, comments) in a database, independent of the HTML/CSS/PHP that controls the look, so that each can be changed without touching the other.

    Answer : Content is maintained by content people – authors and editors – who need no web design knowledge; the developer maintains only the design and the code.

    Answer : Organising, categorising and pushing content to the site through people with assigned roles, an efficient process and suitable tools.

    Answer : A set of web pages, database tables, people and rules that lets users create, edit, approve and publish web content separately from the site design.

    Answer : Because the application only provides tools; without people to create content and rules for approval and publishing, no CMS application can keep a site updated properly.

    Answer : A message board where users post messages; a news site where reporters submit stories for publication; a site where administrators can also change layout, colours and images.

    Answer : Reader/guest, registered user, author, editor (moderator) and administrator.

    Answer : An author composes it (pending); a moderator reviews and edits it; the moderator publishes it; it appears as the newest article on the home page; registered users add comments.

    Answer : They can read published articles and their comments, but cannot post articles or comments.

    Answer : cms_users (accounts and access levels), cms_articles (articles with status and dates) and cms_comments (comments linked to articles and users).

    Answer : By the is_published column (0 = pending, 1 = published), together with submit_date and publish_date.

    Answer : Display pages (home, article, pending list, review), editing pages (compose, user account, control panel), transaction scripts (for users and articles) and include files (header, footer, functions).

    Answer : The PHP code loads the content from the database into variables, and a separate template file only arranges and displays them; changing the template changes the look without changing the code or data.

    Answer : WordPress, Joomla, Drupal and MediaWiki.
    MCQ Answer Key
    No.QuestionCorrect Answer
    1The main reason users return to a web site is:B. Regularly updated content
    2In a CMS, content should be:B. Separate from the design
    3A newly submitted article in the project CMS has the status:B. Pending
    4Who can publish articles in the project CMS?B. Moderators and administrators
    5Which of these is a PHP-based CMS?A. WordPress
    Project 1 : Mini CMS with PHP & MySQLi : Project – A Mini Content Management System with PHP and MySQLi

    Read the notes, run the programs & take the MCQ test »

    Answer : cms_users, cms_articles and cms_comments. Each article has a user_id (author) referencing cms_users; each comment has an article_id referencing cms_articles and a user_id referencing cms_users.

    Answer : In the access_level column: 1 = user (author), 2 = moderator, 3 = administrator.

    Answer : When an article is deleted, all comments that reference it are deleted automatically by the database.

    Answer : session_start(), the time zone, the MySQLi connection and helper functions. Every page requires it, so these settings and functions are written only once.

    Answer : It escapes text with htmlspecialchars() before it is output, protecting the pages against cross-site scripting.

    Answer : It checks whether a user is logged in and has at least the required access level; if not, it redirects to login.php and stops the script.

    Answer : At registration it is stored as password_hash($pass, PASSWORD_DEFAULT); at login the hash is fetched by e-mail and checked with password_verify().

    Answer : To give the logged-in session a new id, preventing session fixation attacks.

    Answer : The session only needs the id, name, e-mail and level; keeping the hash out of the session limits the damage if session data is ever exposed.

    Answer : It is inserted with is_published = 0 (pending). A moderator publishes it in review.php, which sets is_published = 1 and publish_date = NOW().

    Answer : Only published articles (is_published = 1), newest first, with author, publish date and number of comments.

    Answer : After processing a POST (adding a comment) the script redirects to the article page with GET, so refreshing the page does not submit the comment again.

    Answer : A one-time message stored in the session by one request (e.g. "Article published.") and displayed and removed by the next page.

    Answer : Every query that contains outside data uses a prepared statement through $db->execute_query() with ? placeholders; numeric ids are also cast with (int).

    Answer : Categories and search, pagination of the home page, image uploads for articles, comment moderation, an RSS/JSON feed, or CSRF tokens on forms (any three).
    MCQ Answer Key
    No.QuestionCorrect Answer
    1In the project, an access_level of 2 means:C. Moderator
    2A newly composed article is stored with:B. is_published = 0
    3Which function protects pages by role in the project?C. require_level()
    4What prevents a comment from being posted twice when the page is refreshed?B. The Post/Redirect/Get pattern
    5Which statement publishes an article?B. UPDATE cms_articles SET is_published = 1, publish_date = NOW() WHERE article_id = ?