PHP

PHP Comprehensive Guide: From Basics to Advanced


Part 1: PHP Basics & Syntax

What is PHP?

  • PHP is an acronym for "PHP: Hypertext Preprocessor" (The PHP Group, 2024a).
  • It is a widely-used, open-source, general-purpose scripting language especially suited for web development (The PHP Group, 2024a).
  • PHP scripts are executed on the server, and the result is returned to the browser as plain HTML.
  • It is free to download and use.

What Can PHP Do?

  • Generate dynamic page content.
  • Collect form data, send and receive cookies, and encrypt data (The PHP Group, 2024b).
  • Add, delete, and modify data in your database.
  • Create, open, read, write, and close files on the server.
  • Restrict users to access some pages on your website.
  • Output images, PDF files, and even Flash movies (not just HTML).

Basic PHP Syntax

  • A PHP script can be placed anywhere in the document.
  • The default file extension for PHP files is .php.
  • PHP statements are terminated by a semicolon (;) (The PHP Group, 2024c).
<?php
echo "Hello World!";
?>

Comments in PHP (The PHP Group, 2024c)

// This is a single-line comment
# This is also a single-line comment
/* This is a
multi-line comment block */

PHP Case Sensitivity

  • All user-defined functions, classes, and keywords (e.g., if, else, while, echo) are case-insensitive.
  • However, all variables are case-sensitive ($y and $Y are two different variables) (The PHP Group, 2024d).

Variables

  • A variable starts with the $ sign, followed by the name of the variable.
  • A variable name must start with a letter or the underscore character.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • PHP has no command for declaring a variable; it is created the moment you first assign a value to it.
  • PHP is a Loosely Typed Language, meaning it automatically converts the variable to the correct data type depending on its value (The PHP Group, 2024d).

Variable Scope

PHP has three different variable scopes: Local, Global, and Static (The PHP Group, 2024d).

  • A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
  • A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.

The global Keyword
Used to access a global variable from within a function (The PHP Group, 2024d).

<?php
$x = 5;
$y = 10;
function myTest() {
    global $x, $y;
    $y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>

The static Keyword
Normally, when a function is executed, all of its variables are deleted. To keep a local variable from being deleted after the function completes, use the static keyword (The PHP Group, 2024d).

<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}
myTest(); // 0
myTest(); // 1
myTest(); // 2
?>

Echo and Print

  • echo - can output one or more strings. It is marginally faster and does not return any value (The PHP Group, 2024e).
  • print - can only output one string, and always returns 1.
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$cars = array("Volvo","BMW","Toyota");

echo $txt1;
echo "<br>";
echo "Study PHP at $txt2";
echo "My car is a {$cars[0]}";

print "<h2>PHP is fun!</h2>";
?>

Data Types

PHP supports the following data types: String, Integer, Float, Boolean, Array, Object, NULL (The PHP Group, 2024f).

  • String: A sequence of characters, like "Hello world!".
  • Integer: A whole number (no decimals).
  • Float: A number with a decimal point or in exponential form.
  • Boolean: Represents two possible states: TRUE or FALSE.
  • Array: Stores multiple values in one single variable.
  • Object: Stores data and information on how to process that data.
  • NULL: A variable with no value assigned to it.

Part 2: Operators & Control Structures

Operators

Arithmetic Operators: +, -, *, /, % (The PHP Group, 2024i).

Assignment Operators: x = y, x += y, x -= y, x *= y, x /= y, x %= y (The PHP Group, 2024i).

String Operators: . (Concatenation), .= (Concatenation assignment) (The PHP Group, 2024i).

Comparison Operators: ==, ===, !=, !==, >, <, >=, <= (The PHP Group, 2024i).

Logical Operators: and, or, xor, &&, ||, ! (The PHP Group, 2024i).

Conditional Statements

  • if statement - executes some code only if a specified condition is true.
  • if...else statement - executes some code if a condition is true and another code if the condition is false.
  • if...elseif....else statement - selects one of several blocks of code to be executed.
  • switch statement - selects one of many blocks of code to be executed (The PHP Group, 2024j).
<?php
$t = date("H");
if ($t < "10") {
    echo "Have a good morning!";
} elseif ($t < "20") {
    echo "Have a good day!";
} else {
    echo "Have a good night!";
}

$favcolor = "red";
switch ($favcolor) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    default:
        echo "Your favorite color is neither red nor blue!";
}
?>

Loops

  • while - loops through a block of code as long as the specified condition is true.
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true.
  • for - loops through a block of code a specified number of times.
  • foreach - loops through a block of code for each element in an array (The PHP Group, 2024j).
<?php
// while loop
$x = 1;
while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
}

// for loop
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}

// foreach loop
$colors = array("red","green","blue","yellow");
foreach ($colors as $value) {
    echo "$value <br>";
}
?>

Part 3: Functions & Arrays

Functions

A function is a block of statements that can be used repeatedly in a program. Function names are case-insensitive (The PHP Group, 2024k).

<?php
function writeMsg() {
    echo "Hello world!";
}
writeMsg();

// Function with arguments and default value
function setHeight($minheight = 50) {
    echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // uses default 50
?>

Arrays

An array stores multiple values in one single variable. PHP has three types of arrays (The PHP Group, 2024l):

  • Indexed arrays - Arrays with a numeric index.
  • Associative arrays - Arrays with named keys.
  • Multidimensional arrays - Arrays containing one or more arrays.
<?php
// Indexed Array
$cars = array("Volvo","BMW","Toyota");
echo count($cars); // 3

// Associative Array
$age = array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";

// Multidimensional Array
$cars = array(
    array("Volvo",100,96),
    array("BMW",60,59),
    array("Toyota",110,100)
);
echo $cars[0][0].": Ordered: ".$cars[0][1].". Sold: ".$cars[0][2]."<br>";
?>

Part 4: Superglobals & Forms

PHP Superglobals

Superglobals are built-in variables that are always accessible, regardless of scope (The PHP Group, 2024m).

  • $GLOBALS - Used to access global variables from anywhere in the PHP script.
  • $_SERVER - Holds information about headers, paths, and script locations.
  • $_POST - Used to collect form data after submitting an HTML form with method="post".
  • $_GET - Used to collect form data after submitting an HTML form with method="get".
  • $_FILES - Used to upload files from a client computer to the remote server.
  • $_SESSION and $_COOKIE

Form Validation & Security

Security Risk: The $_SERVER["PHP_SELF"] variable can be exploited by hackers using Cross-Site Scripting (XSS) (The PHP Group, 2024n).

Solution: Always use the htmlspecialchars() function. It converts special characters (like < and >) to HTML entities, preventing script injection.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Part 5: Advanced PHP (Dates, Files, Cookies, Sessions)

PHP Date() Function

The date() function formats a timestamp to a more readable date and time (The PHP Group, 2024o).

<?php
echo date("Y/m/d") . "<br>";
echo date("Y.m.d") . "<br>";
echo date("Y-m-d");
?>

Include and Require

  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script if the file is missing.
  • include will only produce a warning (E_WARNING) and the script will continue (The PHP Group, 2024p).

Cookies & Sessions

A cookie is a small file that the server embeds on the user's computer to identify the user (The PHP Group, 2024s). A session solves the HTTP stateless problem by storing information on the server (The PHP Group, 2024t).

  • Start a session using session_start(); (must appear before the <html> tag).
  • Store/Retrieve using the $_SESSION variable.
  • Destroy using unset($_SESSION['views']); or session_destroy();.

Part 6: Error Handling & Exceptions

Exceptions are used to change the normal flow of a script if a specified error occurs. It uses try, throw, and catch (The PHP Group, 2024v).

<?php
function checkNum($number) {
    if($number > 1) {
        throw new Exception("Value must be 1 or below");
    }
    return true;
}

try {
    checkNum(2);
    echo 'If you see this, the number is 1 or below';
} catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
}
?>

References

The PHP Group. (2024a). PHP: Introduction. PHP Manual. https://www.php.net/manual/en/intro-whatis.php

The PHP Group. (2024b). PHP: What can PHP do?. PHP Manual. https://www.php.net/manual/en/intro-whatcando.php

The PHP Group. (2024c). PHP: Basic syntax. PHP Manual. https://www.php.net/manual/en/language.basic-syntax.php

The PHP Group. (2024d). PHP: Variables. PHP Manual. https://www.php.net/manual/en/language.variables.php

The PHP Group. (2024e). PHP: echo. PHP Manual. https://www.php.net/manual/en/function.echo.php

The PHP Group. (2024f). PHP: Types. PHP Manual. https://www.php.net/manual/en/language.types.php

The PHP Group. (2024g). PHP: String functions. PHP Manual. https://www.php.net/manual/en/ref.strings.php

The PHP Group. (2024h). PHP: Constants. PHP Manual. https://www.php.net/manual/en/language.constants.php

The PHP Group. (2024i). PHP: Operators. PHP Manual. https://www.php.net/manual/en/language.operators.php

The PHP Group. (2024j). PHP: Control structures. PHP Manual. https://www.php.net/manual/en/language.control-structures.php

The PHP Group. (2024k). PHP: Functions. PHP Manual. https://www.php.net/manual/en/language.functions.php

The PHP Group. (2024l). PHP: Arrays. PHP Manual. https://www.php.net/manual/en/language.types.array.php

The PHP Group. (2024m). PHP: Superglobals. PHP Manual. https://www.php.net/manual/en/language.variables.superglobals.php

The PHP Group. (2024n). PHP: Form handling. PHP Manual. https://www.php.net/manual/en/tutorial.forms.php

The PHP Group. (2024o). PHP: date. PHP Manual. https://www.php.net/manual/en/function.date.php

The PHP Group. (2024p). PHP: include. PHP Manual. https://www.php.net/manual/en/function.include.php

The PHP Group. (2024q). PHP: Filesystem functions. PHP Manual. https://www.php.net/manual/en/ref.filesystem.php

The PHP Group. (2024r). PHP: Handling file uploads. PHP Manual. https://www.php.net/manual/en/features.file-upload.php

The PHP Group. (2024s). PHP: Cookies. PHP Manual. https://www.php.net/manual/en/features.cookies.php

The PHP Group. (2024t). PHP: Sessions. PHP Manual. https://www.php.net/manual/en/features.sessions.php

The PHP Group. (2024u). PHP: Error handling. PHP Manual. https://www.php.net/manual/en/language.errors.php

The PHP Group. (2024v). PHP: Exceptions. PHP Manual. https://www.php.net/manual/en/language.exceptions.php

The PHP Group. (2024w). PHP: Filters. PHP Manual. https://www.php.net/manual/en/filter.php

The PHP Group. (2024x). PHP: MySQLi. PHP Manual. https://www.php.net/manual/en/book.mysqli.php

The PHP Group. (2024y). PHP: XML Parser. PHP Manual. https://www.php.net/manual/en/book.xml.php

No comments:

Post a Comment