Algo Infinity Verse

Start Your Journey With PHP Programming Learn Backend Basics, Form Processing & Session Management

|
0 Topics
0 Examples
0 Exercises

🐘 Learn PHP

Master server-side web development from simple syntax up to state handling with cookies and sessions.

0 / 13 topics completed
01

Introduction to PHP

PHP (Hypertext Preprocessor) is an open-source, widely-used server-side scripting language designed specifically for web development. Unlike frontend languages (HTML, CSS, JS) that run inside the client's web browser, PHP executes directly on the web server.

When a user requests a page containing PHP, the server processes the PHP code, generates standard HTML dynamically, and sends only the plain HTML back to the browser. This makes it a core engine for backend tasks like data retrieval, session control, and API development.

Why Learn PHP?

  • Easy to Adopt: Its syntax is very logical and friendly for beginners coming from HTML or C-style languages.
  • Powers Most of the Web: Over 75% of websites with known backend technologies run on PHP, including platforms like WordPress, Joomla, and Drupal.
  • Database Integration: Offers native support for relational databases (like MySQL, PostgreSQL, and SQLite).
  • Strong Framework Ecosystem: Powers modern high-productivity backend frameworks like Laravel and Symfony.
Practice: Introduction to PHP

Which statement correctly describes how PHP processes a page request?

  • A) The server sends PHP source code to the browser, which compiles and runs it inside sandbox engines.
  • B) The web server runs the PHP script, generates output (such as HTML), and returns that output to the client's browser.
  • C) PHP compiles CSS and Javascript stylesheets into binary objects on the client machine.
  • D) PHP is a database server that replaces SQL engines.

Correct Answer: B

Explanation: PHP is a server-side language. The server runs the script, builds the final HTML text, and returns only that HTML to the client browser, keeping the database logic and secret code hidden.

02

PHP Setup & Local Server Guide

To run PHP locally, you need a server environment. The easiest way is using one-click installation packages containing Apache (web server), PHP, and MySQL.

Popular Local Server Packages

  • XAMPP (Windows, macOS, Linux): The most popular cross-platform local server setup.
  • WAMP (Windows): A great lightweight option specifically tailored for Windows.
  • Laravel Valet / Herd (macOS/Windows): Highly optimized developers tools that run ultra-fast background services without Apache.

PHP Built-in Server

If you already have PHP installed on your terminal, you can start a development server immediately without installing third-party GUI applications:

CLI
php -S localhost:8000
💡

When using XAMPP, you must place your files in the htdocs folder. On WAMP, place them inside www. You then run them by visiting http://localhost/your-file.php in your web browser.

Practice: Local Server Setup

When running a local XAMPP Apache server, what folder directory must your PHP project files be saved in to resolve on localhost?

Answer: htdocs

Explanation: Apache in XAMPP defaults its document root to the `htdocs` directory (located inside the XAMPP installation directory). Files saved there are resolved relative to `http://localhost/`.

03

PHP Syntax Basics

PHP scripts are embedded inside standard HTML pages using specific delimiter tags. A PHP code block starts with <?php and ends with ?>.

PHP
<?php
// Single-line comment
# Another single-line comment

/*
  Multi-line
  comment block
*/

echo "Hello from PHP!";
?>

Core Syntax Rules

  • Semicolons: Every PHP statement must end with a semicolon (;). Leaving it out triggers syntax parse errors.
  • Case Sensitivity: Variable names are fully case-sensitive (e.g. $x and $X are different). However, built-in functions, keywords (like if, else, echo), and classes are case-insensitive.
Practice: Syntax Basics

Which of the following will result in a syntax error in PHP?

  • A) echo "Hello";
  • B) ECHO "Hello";
  • C) $val = "A" $val2 = "B";
  • D) // print "Hello";

Correct Answer: C

Explanation: Semicolons are required to terminate statements. Failing to place a semicolon between the assignment of `$val` and `$val2` causes a parse error.

04

Variables and Data Types

In PHP, variables start with a dollar sign ($) followed by the variable name. PHP is a loosely typed language, meaning you do not need to define its data type upon creation.

PHP
<?php
$name = "John Doe";     // String
$age = 30;              // Integer
$price = 19.99;         // Float (Double)
$isActive = true;       // Boolean
$fruits = ["Apple", "Banana"]; // Array
$empty = null;          // NULL

var_dump($name);
var_dump($price);
?>
Output
string(8) "John Doe"
float(19.99)

Naming Rules for Variables

  • Must start with a letter or an underscore (_), never a number or special symbol.
  • Can only contain alphanumeric characters and underscores (a-z, A-Z, 0-9, and _).
  • Variable names are case-sensitive ($myVar and $myvar are completely separate).
Practice: Variables & Types

Which of the following is an invalid variable name in PHP?

  • A) $_totalAmount
  • B) $user_1
  • C) $1stUser
  • D) $userAge

Correct Answer: C

Explanation: PHP variables cannot start with numbers. Therefore, `$1stUser` is invalid, whereas letters and underscores are permitted starting symbols.

05

Operators

Operators are symbols that tell the compiler to perform specific mathematical, logical, or string actions.

Category Operators Examples & Description
Arithmetic + - * / % ** $a ** $b (Exponentiation), $a % $b (Modulus)
Comparison == === != !== > < === strict equality checks both value and type.
Logical && || ! xor Combine conditional checks. xor returns true if only one operand is true.
String . .= . concatenates strings; .= appends to an existing string.
PHP
<?php
$greeting = "Hello ";
$name = "Alice";
$fullMessage = $greeting . $name; // Concatenation
echo $fullMessage;

$x = 5;
$y = "5";
var_dump($x == $y);  // true (values match)
var_dump($x === $y); // false (integer vs string)
?>
Output
Hello Alice
bool(true)
bool(false)
Practice: Operators

If $a = 10; $b = "10";, what will be the outputs of var_dump($a === $b); and var_dump($a !== $b);?

Answer: false and true

Explanation: Strict comparison `===` checks both data types, and since integer 10 doesn't match string "10", `===` evaluates to `false`. Strict inequality `!==` checks if they are not identical, which is `true`.

06

Input and Output (echo, print, var_dump)

PHP offers distinct ways to output data. Choosing the right built-in is important for structure and debugging.

Differences between echo, print, and var_dump

  • echo: A language construct (not a function). It can take multiple arguments, does not return a value, and is marginally faster.
  • print: Also a language construct, but behaves like a function because it always returns the value 1. It only takes one string argument.
  • var_dump(): A debugging function. It prints out a variable's data type, byte length, and its value, making it critical for analyzing arrays and objects.
PHP
<?php
echo "Hello", " ", "World!"; // Multiple parameters

$result = print("Welcome! ");
echo $result; // Will output 1

$arr = [1, "PHP", false];
var_dump($arr);
?>
Output
Hello World!
Welcome! 1
array(3) {
  [0]=> int(1)
  [1]=> string(3) "PHP"
  [2]=> bool(false)
}
Practice: Input and Output

Which output command is best suited to inspect the underlying structure and item data types of an array?

  • A) echo
  • B) print
  • C) var_dump()
  • D) print_r() without types

Correct Answer: C

Explanation: `var_dump()` output includes values along with their types (e.g. `int`, `string`, `bool`) and string sizes, which is vital for thorough debugging.

07

Conditional Statements

Conditional statements are used to perform different actions based on different conditions. PHP supports if, else, elseif, and switch.

PHP
<?php
$score = 82;

if ($score >= 90) {
    echo "Grade A";
} elseif ($score >= 80) {
    echo "Grade B";
} else {
    echo "Grade C";
}

$favColor = "red";
switch ($favColor) {
    case "blue":
        echo "Your color is blue.";
        break;
    case "red":
        echo "Your color is red.";
        break;
    default:
        echo "Unknown color.";
}
?>
Output
Grade BYour color is red.

Null Coalescing Operator (??)

Introduced in PHP 7, this operator checks if a variable exists and is not null; otherwise, it returns a default value. It is highly useful when reading parameters.

$username = $_GET['user'] ?? 'Guest';
Practice: Conditionals

What will happen in a switch statement block if a case matches, but there is no break; statement at the end of that case?

Answer: Fall-through behavior

Explanation: If you omit a `break;` statement, execution will continue (fall through) into the next case statement, executing its code regardless of whether the case criteria matches, until it hits a `break;` or the end of the switch block.

08

Loops

Loops allow you to execute a block of code repeatedly as long as a specified condition is met. PHP supports for, while, do-while, and foreach.

PHP
<?php
// For Loop
for ($i = 1; $i <= 3; $i++) {
    echo "For count: $i ";
}

// While Loop
$w = 1;
while ($w <= 3) {
    echo "While count: $w ";
    $w++;
}

// Foreach Loop (traversing arrays)
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo "Color: $color ";
}
?>
Output
For count: 1 For count: 2 For count: 3 While count: 1 While count: 2 While count: 3 Color: red Color: green Color: blue 
Practice: Loops

Which loop construct is specifically designed and optimized to iterate through the elements of an array without needing counter variables?

  • A) for loop
  • B) while loop
  • C) do-while loop
  • D) foreach loop

Correct Answer: D

Explanation: The `foreach` loop is specifically designed to iterate over arrays and objects in PHP. It automatically moves the internal array pointer forwards with each iteration.

09

Functions

A function is a block of statements that can be used repeatedly in a program. It will not execute automatically when a page loads; instead, it runs when called.

PHP
<?php
// Default value parameter
function greet($name = "Guest") {
    return "Hello, $name!";
}

echo greet("Bob");
echo "\n";
echo greet(); // Uses default

// Strict type declaration (optional)
function addNumbers(int $a, int $b): int {
    return $a + $b;
}
?>
Output
Hello, Bob!
Hello, Guest!
Practice: Functions

Given the function: function calc($val = 5) { return $val * 2; }, what is the output of echo calc();?

Answer: 10

Explanation: Because no argument is passed during the function call `calc()`, PHP defaults `$val` to `5`. It then returns `5 * 2 = 10`.

10

Arrays

An array stores multiple values in one single variable. PHP supports three types of arrays.

Types of Arrays

  • Indexed Arrays: Arrays with numeric keys. (e.g. $arr = ["a", "b"]; where key 0 is "a" and key 1 is "b").
  • Associative Arrays: Arrays with named keys that you assign. (e.g. $age = ["Peter" => 35];).
  • Multidimensional Arrays: Arrays containing one or more nested arrays.
PHP
<?php
// Associative Array
$person = [
    "name" => "Alice",
    "age" => 25,
    "skills" => ["PHP", "MySQL"] // Nested Array
];

echo $person["name"]; // Alice
echo $person["skills"][0]; // PHP
?>
Practice: Arrays

How do you fetch the value "Green" from the array: $palette = ["primary" => "Red", "secondary" => "Green"];?

  • A) $palette[1]
  • B) $palette["secondary"]
  • C) $palette->secondary
  • D) $palette.secondary

Correct Answer: B

Explanation: For associative arrays, you access elements using square brackets containing the string key, hence `$palette["secondary"]` is the correct notation.

11

Forms Handling (GET and POST)

The PHP superglobals $_GET and $_POST are used to collect form data after submitting an HTML form.

Feature GET Method POST Method
Visibility Data is visible in the URL query string (e.g. ?name=Alice) Data is embedded inside the HTTP request body (invisible in URL)
Size Limits Limited (typically around 2000 characters) Large / Unlimited (allows file uploads)
Security Poor (never use for passwords or confidential variables) Better (data is not cached in browser histories)

Preventing Cross-Site Scripting (XSS)

When outputting raw user input, attackers can inject malicious Javascript code. Always wrap output in htmlspecialchars() to convert special HTML symbols into benign text entities.

echo htmlspecialchars($_POST["username"]);
PHP Form Processing Example
<!-- form.html -->
<form method="POST" action="welcome.php">
    Name: <input type="text" name="fname">
    <input type="submit">
</form>

<?php
// welcome.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitizing user input for safety
    $name = htmlspecialchars($_POST['fname']);
    echo "Welcome, " . $name;
}
?>
Practice: Forms Handling

Which function should you wrap around $_POST/$_GET output inside HTML tags to block Cross-Site Scripting (XSS) injections?

  • A) var_dump()
  • B) htmlspecialchars()
  • C) session_start()
  • D) urlencode()

Correct Answer: B

Explanation: `htmlspecialchars()` converts special characters (like `<` and `>`) into HTML entities (like `<` and `>`), rendering them as static text instead of executable scripts in the browser.

12

Basic Superglobals

Superglobals are built-in global variables that are always accessible, regardless of scope - meaning you can access them from any class, function, or file without needing to declare global $var;.

Core PHP Superglobals

  • $_SERVER: Contains paths, script locations, and server/header variables.
  • $_GET: Holds an associative array of URL query parameters.
  • $_POST: Holds an associative array of variables passed via HTTP POST.
  • $_COOKIE: Associative array of client cookies sent to the server.
  • $_SESSION: Associative array containing session variables active for the current visitor.
PHP
<?php
// Display server name and visitor User Agent headers
echo $_SERVER['SERVER_NAME'];
echo "\n";
echo $_SERVER['HTTP_USER_AGENT'];
?>
Practice: Superglobals

Which superglobal would you read to verify the client browser's HTTP User Agent or request header methods (e.g. GET vs POST)?

Answer: $_SERVER

Explanation: `$_SERVER` houses all headers, client connection parameters, script execution settings, and local hosting values (such as `$_SERVER['HTTP_USER_AGENT']` and `$_SERVER['REQUEST_METHOD']`).

13

Intro to Sessions & Cookies

HTTP is stateless, meaning the server forgets who you are between requests. Cookies and Sessions allow you to preserve states and variables across pages.

Cookies vs Sessions

  • Cookies: Stored directly on the client's browser. They can persist for a long time but are easily inspected or edited by the user, making them unsafe for sensitive data.
  • Sessions: Stored securely on the server. The client's browser only stores a temporary Session ID Cookie (PHPSESSID) to identify themselves.

Starting a Session:

PHP - Sessions
<?php
// Must be called at the very top before any HTML output
session_start();

// Setting a session variable
$_SESSION["userid"] = 101;
$_SESSION["role"] = "admin";

// Accessing it on another page
echo "User: " . $_SESSION["userid"];
?>

Setting a Cookie:

PHP - Cookies
<?php
// setcookie(name, value, expire_time, path)
// Expire in 1 hour (3600 seconds)
setcookie("user", "Alex", time() + 3600, "/");

// Retrieving cookies on subsequent requests
echo $_COOKIE["user"] ?? "Not logged in";
?>
Practice: Sessions & Cookies

Which function MUST be executed at the absolute top of a PHP script (before any HTML/output is sent) to access or modify the $_SESSION array?

  • A) session_create()
  • B) session_start()
  • C) setcookie()
  • D) session_register()

Correct Answer: B

Explanation: `session_start()` initiates/resumes a session. It sends header cookies behind the scenes, so it must be executed before printing any characters or tags, otherwise PHP throws a "Headers already sent" warning.