PHP master class

Fundamental concepts

  • HTTP request life cycle
  • Interpreters and compilers
  • Data types

HTTP Request Life-cycle

ISP

Browser

Client (You)

Request

Forwards the request to ISP

What is the IP for the request server?

192.168.1.1

ISP replies to the browser with the IP

Pings the IP with the request

Responds with the web page content

DBMS

192.168.1.1's server

Web page components

Interpreters & Compilers

Compiler

Interpreter

Compilers

Compiler

Compilers

JIT Compiler

Profiler

Interpreter

Compiler

Lexer

AST

Output

Optimized code

Parsed tokens

Generated bytecode

Type System in PHP

Variables, type system, and control flow

  • Variables && constants
  • Data types
  • Operators
  • Type coercion
  • Typecasting/juggling
  • Control flow
<?php

$name = "Ahmed";
$age = 19;
$profession = "web developer";

const PI = 3.14;
const SECONDS_IN_DAY = 86400;

How variables are stored?

Variables and consts

Memory address Label Value permission
0x6dfed4 name "ahmed" rw
0x7abcd5 age 19 rw
<?php

$name = "ahmed";

$age = 19;

$profession = "web development";

Variables and consts

<?php


const SECONDS_IN_DAY = 86400;
const PI = 3.14;
Memory address Label Value Permission
0xfcdebe SECONDS_IN_DAY 86400 r
0xfac28e PI 3.14 r

PHP data types

  1. Strings (texts, characters)
  2. Numbers (integers/floats)
  3. Booleans (true/false)
  4. NULL
  5. Arrays
  6. Objects (Custom types)
  7. Resources
  8. Callbacks

Primitive data types

Strings

Bools

Numbers

NULL

Integers

Floats

True

False

"ahmed"

1,2,3,4

3.14 , 2.78

Arrays

Arrays is a collection of data types that could contain any other data type within it

<?php

$names = ['ahmed', 'mohamed', 'mahmoud'];

$numbers = [1, 2, 3, 4, 5, 6];

$users = [
    [
        'username' => 'ahmed.osama0',
        'full_name' => 'Ahmed Osama',
        'id' => '19121640',
        'phone_number' => '01153820570',
        'card_number' => '4242 4242 4242 4242',
        'languages' => ['arabic', 'english', 'spanish']
    ],
];

Arrays

elements in an array are indexed from the 0th index to nth

<?php

//           0         1          2
$names = ['ahmed', 'mohamed', 'mahmoud'];

$numbers = [1, 2, 3, 4, 5, 6];

Arrays

Unless they're given some sort of special identifier known as the key

<?php

$user = [
    'username' => 'ahmed',
    'age' => 19,
    //                0          1
    'languages' => ['php', 'javascript']
];

Arrays

Accessing elements is done through its key or index

<?php

$user = [
    'username' => 'ahmed',
    'age' => 19,
    //                0          1
    'languages' => ['php', 'javascript']
];


var_dump($user); // returns the whole array

Arrays

Accessing elements is done through its key or index

<?php

$user = [
    'username' => 'ahmed',
    'age' => 19,
    //                0          1
    'languages' => ['php', 'javascript']
];

var_dump($user['username']); // returns ahmed
var_dump($user['languages']); // returns the array of languages
var_dump($user['languages'][0]); // returns php

Arrays

Changing elements within an array

<?php

$user = [
    'username' => 'ahmed',
    'age' => 19,
    //                0          1
    'languages' => ['php', 'javascript']
];

$user['username'] = 'Mohamed';
$user['age'] = 28;
$user['languages'] = ['golang', 'python'];

Arrays

Array destructuring

The process of extracting values out of an array

<?php

$user_info = [
	'first_name' => 'ahmed',
	'last_name' => 'osama',
	'languages' => ['arabic', 'english', 'spanish'],
	'skills' => [
		'techincal' => [
			'languages' => ['php', 'javascript'],
			'frameworks' => ['laravel', 'nest.js', 'react.js', 'vue.js']
		],
		'public speaking',
		'instructing'
	]
];

// Extract these information to corresponding variables

Operators

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Spread operator
  • Conditional and logical operators

Operators

<?php

// Arithmetic operators (+ - * / ** ^ ++ -- %)
var_dump(5 ** 2); // 25
var_dump(4 % 2); // 2
var_dump(5 % 2); // 1









$x = 1;
var_dump($x++); // 1




$y = 1;
var_dump($y); // 1








$w = 1;
var_dump(++$w); // 2








$z = 1;
var_dump(--$z); // 0
















// Assignment operators ( = += -= %= /= *= .= )

$x = 'ahmed osama';
$x .= 'el-morsy';






$x = 1;
$x += 2; // $x = $x + 2;













// Comparison operators ( == === != <> <= >= < > <=> )

var_dump(1 == 1); // true
var_dump(3 > 2); // true






var_dump(5 <= 4); // false
var_dump(3 != 3); // false
var_dump(4 <> 4); // false







var_dump(3 <=> 4); // -1
var_dump(4 <=> 4); // 0
var_dump(5 <=> 4); // 1












// Spread operator ( ... )

$arr1 = [1,2,3,4,5];

$arr2 = [...$arr1];










// Conditional and logical operators ( [and &&] [OR ||] [not !] [ternary ?:] [null ??] )

var_dump(2 && 1); // true
var_dump(0 && 1); // false
var_dump(-0 || 0); // false



var_dump(!0); // true
var_dump(!-0); // true





$x = 0 ? 1 : 2; // $x = 2
$x = 1 ? 0 : 2; // $x = 0
$x = true ?: false; // $x = true




$y = 0 ?? 1; // $y = 0
$y = true ?? null; // $y = null
$y = null ?? false; $y = false

Type coercion

Type coercion is when the language attempts to change the type of a variable to another type to suit the flow of the program.

<?php

var_dump(true == 1); // true




var_dump(false == 0); // true




var_dump('42' == 42); // true




var_dump(0 == -0); // true




var_dump(true == '1'); // true




var_dump(3 > 2 > 1); // parse error
var_dump((3 > 2) > 1); // false




var_dump(true === 1); // false




var_dump(false === 0); // false




var_dump('42' === 42); // false





var_dump(0 === -0); // true

Typecasting

Typecasting is taking the shape of a data type and hardly shape another type to the desired data type same as casting iron.

<?php

var_dump((int) 'ahmed'); // 0
var_dump((int) '42ahmed'); // 42

var_dump((array) 'ahmed'); // ['ahmed']

var_dump((object) 'ahmed'); // class stdClass { public $scalar = 'ahmed'; }

var_dump((string) -0); // "0" [Wrong answer]

Control flow

  • If statements
  • Switch case
  • Match expression
  • For loop
  • Foreach
  • While loop
  • Do while

Control flow

<?php

if ($condition) {
    # code...
}





switch ($variable) {
    case 'value':
        # code...
        break;

    default:
        # code...
        break;
}





$value = match ($variable) {};









for ($i=0; $i < 5; $i++) {
    # code...
}









foreach ($variable as $key => $value) {
    # code...
}







while ($a <= 10) {
    # code...
}







do {
    # code...
} while ($a <= 10);

Functions

<?php

function add($x, $y)
{
    return $x + $y;
}

$add = function ($x, $y) {
    return $x + $y;
};

$add = fn ($x, $y) => $x + $y;
A function is a process that is done on some certain data that the function receives through its inputs (parameters) and return them to the outside world as outputs.

Parameters of the function

Functions

<?php

function add($x, $y)
{
    return $x + $y;
}

$add = function ($x, $y) {
    return $x + $y;
};

$add = fn ($x, $y) => $x + $y;
A function is a process that is done on some certain data that the function receives through its inputs (parameters) and return them to the outside world as outputs.

Parameters of the function

Normal fn

Functions

<?php

function add($x, $y)
{
    return $x + $y;
}

$add = function ($x, $y) {
    return $x + $y;
};


$add = fn ($x, $y) => $x + $y;

Functions

<?php

function add(int $x, int $y): int
{
    return $x + $y;
}

Types within functions

Type hinting

Return Types

Functions' EC

function add(int $x, int $y): int
{
    return $x + $y;
}

Local
Memory

Execution

Return Value

$x

$y

Functions' EC

$x

$y

function add(int $x, int $y): int
{
    return $x + $y;
}

Local
Memory

Execution

Return Value

$value = add(2, 3);

2

3

return $x + $y;

Functions' EC

$x

$y

function add(int $x, int $y): int
{
    return $x + $y;
}

Local
Memory

Execution

Return Value

$value = add(2, 3);

2

3

=

=

return $x + $y;

}

5

Functions' EC

$x

$y

function add(int $x, int $y): int
{
    return $x + $y;
}

Local
Memory

Execution

Return Value

$value = 5;

5

Callstack

function add(int $x, int $y): int
{
    return $x + $y;
}
function subtract(int $x, int $y): int
{
    return add($x, -$y);
}
function increase(int $x): int
{
    return add($x, 1);
}
function decrease(int $x): int
{
    return add($x, -1);
}
<?php

var_dump(
    increase(
        decrease(
            add(
                2,
                add(
                    3,
                    increase(
                        decrease(
                            subtract(5, 3)
                        )
                    )
                )
            )
        )
    )
);

Subtract(5, 3)

add(5, -3)

  • Variable references
  • Static variables
  • Array and string functions
  • Output buffering
  • working with files

More variables and functions

Variable reference

<?php

$x = [1, 2, 3];

$y = $x;

$y[] = 4;

var_dump($x); // [1, 2, 3];
























$x = [1, 2, 3];

$y =& $x;

$y[] = 4;

var_dump($x); // [1, 2, 3, 4];

Static variables

function counter()
{
    static $counter = 1;

    return ++$counter;
}

var_dump(counter());
var_dump(counter());
var_dump(counter());
var_dump(counter());














function sum(...$numbers)
{
    static $result = 0;

    if (count($numbers) === 0) {
        return $result;
    }

    $result = $result + $numbers[0];

    return sum(...array_slice($numbers, 1));
}

var_dump(sum(1, 2, 3, 4, 5)); // 15

Array functions

The most used array functions to manipulate your arrays.

  • array_walk() walks through the array and modifies every element within it to apply a callback function on it.
  • array_map() similar to array_walk() but it doesn't modify the original array, instead, it returns a new copied array.
  • array_filter() filters through your array based on a predicate function
  • array_reduce() Combines two items together to become one item through an operation defined by a function

Output buffering

Output buffering functions are used to control the output of your PHP file before sending it to the browser to view.

  • ob_start() turns on output buffering i.e. creates a buffer to hold the output
  • ob_get_contents() returns the data gathered since the ob started
  • ob_clean() removes everything from the buffer
  • ob_flush() outputs content from the buffer without removing the stored content in the buffer
  • ob_end_clean() it runs ob_get_contents() and turns off the buffering.
  • ob_end_flush() runs ob_flush() and turns off the buffering

Working with files

File operations

Read

  • file_get_contents() reads the file into a string
  • file() reads the file into an array where each line represents an item
  • readfile() reads the file into a string and outputs it to the browser

Working with files

File operations

fopen()

<?php

$f = fopen( // Opens a file and stores the resource in $f

);














$f = fopen(
	string $filename, // path to the file
	string $mode, // the mode with which you'll open the file
	[
		bool $use_include_path = FALSE,
			resource $context
	]
);

Working with files

File operations

$mode

Access mode What it means
r / r+ Read (+write) at the beginning of the file

Working with files

File operations

$mode

Access mode What it means
r / r+ Read (+write) at the beginning of the file
w / w+ Write (+read), starts at the beginning

Working with files

File operations

$mode

Access mode What it means
r / r+ Read (+write) at the beginning of the file
w / w+ Write (+read), starts at the beginning
a / a+ Write (+read), at the end

Working with files

File operations

$mode

Access mode What it means
r / r+ Read (+write) at the beginning of the file
w / w+ Write (+read), starts at the beginning
a / a+ Write (+read), at the end
x / x+ Creates and write (+ read), fails if the file exists

Working with files

File operations

$mode

Access mode What it means
r / r+ Read (+write) at the beginning of the file
w / w+ Write (+read), starts at the beginning
a / a+ Write (+read), at the end
x / x+ Creates and write (+ read), fails if the file exists
c / c+ Open for write (+read), without truncating the file

Working with files

file functions

Reading

Writing

  • fread()
  • feof()
  • fget*
    • ​fgets()
    • fgetc()
    • fgetcsv()
  • Temporary files
    • tmpfile()
    • tempnam()
  • Permanent files
    • fopen()
    • touch()

Creating

  • fwrite()
  • file_put_contents()
  • fput*
    • ​fputs()
    • fputcsv()

Variables again and HTTP requests again

  • Variable scope
  • Superglobal variables
  • Sessions and cookies
  • Regular expressions

Variable scopes

  • Global scope
  • Local scope
  • Lexical scope

Variable scopes

Global Scope

All the variables that are accessible anywhere in your file

<?php

$array = [1, 2, 3];

function foo()
{
    foreach ($array as $item) {
        echo $item;
    }
}

Variable scopes

Global Scope

All the variables that are accessible anywhere in your file

<?php

$array = [1, 2, 3];

function foo()
{
    global $array;
    // $arr = $GLOBALS['array'];

    foreach ($array as $item) {
        echo $item;
    }
}

Variable scopes

Local Scope

The variables defined within a function and only accessible within the function

<?php

function sayHello(string $name): string
{
    $title = 'Mr.';

    return "Hello, {$title} {$name}";
}

Variable scopes

Lexical scope

The variables defined within a function and only accessible within the function

<?php

function greet($greeting)
{
    return function ($name) use ($greeting) {
        return "${greeting} ${name}";

        // return fn ($name) => "${greeting} ${name}";
    };
}

Super global variables

  • $GLOBALS
  • $_POST, $_GET, $_REQUEST
  • $_SERVER
  • $_SESSION and $_COOKIE

Super global variables

$_POST, $_GET, $_REQUEST

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Form request</title>
</head>

<body>
    <form action="index.php" method="POST">
        <input type="text" name="first_name">
        <input type="text" name="last_name">
        <input type="submit" />
    </form>
</body>
</html>
<?php

var_dump($_POST);

var_dump($_GET);

var_dump($_REQUEST);
  1. $_POST stores the variables sent using the POST verb
  2. $_GET stores the variables sent using the GET verb
  3. $_REQUEST stores any variable using any verb

Super global variables

$_SERVER

<?php

var_dump($_SERVER);

Stores data about the server and the client sent the request.

<?php

['REMOTE_ADDR' => $ip] = $_SERVER; // getting the client IP address

Sessions and cookies

COOKIES

HTTP is stateless

Sessions and cookies

COOKIES

But if HTTP is stateless, how can we store our data?

Websites

Me randomly browsing the web

Sessions and cookies

COOKIES PROPERTIES

Stored in the client side

Stores up to 4KB of data

Can be accessed by the domains created them only

You can store at least 50 cookie per domain

Improves user experience but has security concerns

Sessions and cookies

SETTING COOKIES

<?php

setcookie(
    string $name,
    string $value = "",
    int $expires = 0,
    string $path = "",
    string $domain = "",
    bool $secure = false,
    bool $httponly = false
): bool















setcookie(string $name, string $value = "", array $options = [
	int $expires = 0,
	string $path = "",
	string $domain = "",
	bool $secure = false,
	bool $httponly = false,
	string $samesite = "Strict" // None || Lax || Strict
]);

Sessions and cookies

COOKIE MANIPULATION

<?php

// To update a cookie you just reset the value of a cookie

setcookie('name', 'ahmedosama');

// The next request

setcookie('name', 'mahmoud');



















// To delete a cookie, just add time() - x to the expiry field

setcookie('name', 'ahmedosama', time() + 86400); // a cookie for 24 hours

// the next request

setcookie('name', 'ahmedosama', time() - 3600); // Deletes a cookie as you're setting
// it backwards, NOTE: 3600 is just an arbitrary number.

Sessions and cookies

SESSIONS

Stored in the server side

Sessions are internal cookies

$_SESSION is defined by default

SESSIONS cannot store resources

SESSIONS have some security concerns must be considered

PHP master class from basics to advanced

By Security Theater

PHP master class from basics to advanced

The slides used in the Denizey Platform backend track and our course for PHP mastery

  • 103