Completed

PHP Beginner / Intermediate

Suruhanjaya Pencegahan Rasuah Malaysia

Date
29 Jul โ€“ 3 Aug 2021
Organised by
RH Dynamic Resources
Trainer
Azman Zakaria
Attendees
17

Kursus ini berkonsepkan From Zero to Hero . Peserta dianggap telah mempunyai asas dalam pengaturcaraan, tetapi pemula kepada PHP. Peserta seharusnya telah mempunyai asas HTML, CSS dan SQL yang baik untuk mendapat hasil sepenuhnya dari kursus ini. 

Tools yang akan digunakan didalam kelas ini adalah seperti berikut :-

  • Laragon Full versi 4.0
  • PHP 8.0
  • MySQL 5.7
  • jQuery 3
  • Twitter Bootstrap 5
  • Visual Studio Code
  • SQL Yog
  • Composer
  • Cmder

Dicadangkan PC yang akan digunakan ialah menggunakan Window 10 dengan RAM 8 Gb, dan kapasiti Storage yang Free sebanyak min 2 Gb

Syllabus

Module 1: Using PHP
- Introduction
- Installation PHP
- Embedding PHP
- Outputting Text
- Installing a Web Server (Apache 2.x)
- Hello World
- Compile and Parse
- Comments

Module 15: Abstract
- Abstract Methods
- Abstract Example
- Abstract Classes and Interfaces
- Abstract Guideline

 

 

Module 2: Variables
- Defining Variables
- Data Types
- Integer Type
- Floating-Point Type
- Bool Type
- Null Type
- Default Values

Module 16: Traits
- Inheritance and Traits
- Trait Guidelines

 

 

Module 3: Operators
- Arithmetic Operators
- Assignment Operators
- Combined Assignment Operators
- Increment and Decrement Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Operator Precedence
- Additional Logical Operators

Module 17: Importing Files
- Include Path
- Require
- Include_once
- Require_once
- Return
- _Autoload

 

Module 4: String
- String Concatenation
- Delimiting Strings
- Heredoc Strings
- Nowdoc Strings
- Escape Characters
- Character Reference
- String Compare

Module 18: Type Declarations
- Argument Type Declarations
- Return Type Declarations
- Strict Typing

 

 

Module 5: Arrays
- Numeric Arrays
- Associative Arrays
- Mixed Arrays
- Multi-Dimensional Arrays
Module 19: Type Conversions
- Explicit Casts
- Set type
- Get type
Module 6: Conditionals
- If Statement
- Switch Statement
- Alternative Syntax
- Mixed Modes
- Ternary Operator
Module 20: Variable Testing
- Isset
- Empty
- Is_null
- Unset
- Null Coalescing Operator
- Determining Types
- Variable Information
Module 7: Loops
- While Loop
- Do-while Loop
- For Loop
- Foreach Loop
- Alternative Syntax
- Break
- Continue

Module 21: Overloading
- Property Overloading
- Method Overloading
- Isset and unset Overloading

 

 

 

Module 8: Functions
- Defining Functions
- Calling Functions
- Function Parameters
- Default Parameters
- Variable Parameter Lists
- Return Statement
- Scope and Lifetime
- Anonymous Functions
- Closures
- Generators
- Built-in Functions

Module 22: Magic Methods
- _ToString
- _Invoke
- Object Serialization
- _Sleep
- _Wakeup
- Set State
- Object Cloning

 

 

Module 9: Class
- Instantiating an Object
- Accessing Object Members
- Initial Property Values
- Constructor
- Destructor
- Case Sensitivity
- Object Comparison
- Anonymous Classes
- Closure Object
Module 23: User Input
- HTML Form
- Sending with POST
- Sending with GET
- Request Array
- Security Concerns
- Submitting Arrays
- File Uploading
- Superglobals
Module 10: Inheritance
- Overriding Members
- Final Keyword
- Instance of Operator
Module 24: Namespaces
- Creating Namespaces
- Nested Namespaces
- Alternative Syntax
- Referencing Namespaces
- Namespace Aliases
- Namespace Keyword
- Namespace Guideline

Module 11: Access Levels
- Private Access
- Protected Access
- Public Access
- Var Keyword
- Object Access
- Access Level Guideline

 

 

Module 25: Database
- Setting Up the Database Connection
- Initializing all Includes in one file
- Init file inclusion reminder
- Creating the Database Class
- Future Update for database class
- Automatic DB Connection Setup
- The Query Method
- Database Class Helper Methods
- Testing Query Method
- Improving our Connection to be more OOP

Module 12: Static
- Referencing Static Members
- Static Variables
- Late Static Bindings


 

Module 26: Workshop 1
- Develop a simple application which demonstrate all PHP features
- Login
- Authorization
- Create, Retrieve, Update, Delete (CRUD)
- Pagination
- Layout / template management

Module 13: Constants
- Constant Guideline
- Magic Constants

 

 

 

 

Module 27: Workshop 2
- Continuation from workshop 1
- Session
- Upload / download
- Audit trail
- Fail and folder management (create, copy, rename, delete, list)
- Pdf, Excel generation
- Twitter Bootstrap 5 integration
- More CRUD sample
- Conclusion and closing
Module 14: Interface
- Interface Signatures
- Interface Example
- Interface Usages
- Interface Guideline
 

 

 

 

 

 





 

 

Trainer Profile

 Nama : Azman bin Zakaria
 Umur : 52 tahun
 Pengalaman Dalam Bidang IT : 21 Tahun
 Syarikat : Favourite Trainer Sdn Bhd
 Kelulusan :

  • Bachelor IT UiTM
  • Diploma Computer Science UiTM
  • HRDF Certified Instructor

Azman merupakan senior programmer yang passionate dalam bidang pengaturcaraan komputer dari awal mulai beliau bekerja pada tahun 2000 sehingga hari ini. Beliau mempunyai pengalaman bekerja yang luas di agensi kerajaan, swasta dan sebagai freelancer.
Antara pengaturcaraan yang selalu digunakan adalah seperti :

  • PHP (sejak tahun 2000)
  • PHP dan Laravel Framework
  • PHP dan Yii Framework
  • Coldfusion
  • Java 
  • Java dan Spring Boot Framework
  • Javascript
  • jQuery
  • Vuejs
  • Angular
  • Flutter

 

Notes

In this module we will discuss about history of PHP and then proceed to installation of required tools.

Introduction

Created by Ramus Lerdorf in 1994 as a personal homepage. PHP versioning / years are as follows:

PHP 8.0 2021
PHP 7.4 2020
PHP 7.3 2019
PHP 7.2 2017
PHP 7.1 2016
PHP 7.0 2015
PHP 5.6 2014
PHP 5.5 2012
PHP 5.3 2009
PHP 5.2 2004
PHP 4.0 2000
PHP 1.0 1995


Installation PHP

The following installer is for the purpose of the development stage only.  For the production server, please install one by one for each software. Installer Options are :

  • Laragon
  • XAMPP
  • WAMP
  • MAMP

1. go to https://laragon.org download full software

2. go to https://php.net and download PHP 8 for windows 64 bit
 - unzip and put into laragon/bin/php


Embedding PHP

<?php
$name = 'Azman';
?>

<h1>Hello <?= $name ?></h1>


Outputting Text

<?php
echo "<h2>PHP is Fun!</h2>";
print "<h2>PHP is Fun!</h2>";
$name = 'Azman';
?>

<?= $name ?>


Installing a Web Server (Apache 2.x)

By default, laragon already install Apache 2.x. Other than Apache, PHP also can run on NGINX and Microsoft IIS.


Hello World

1. create a file in module1/index.php and type the following code.

<?php
echo "Hello World";

2. Open a browser and type http://localhost/php8tot/module1/index.php

Compile and Parse

PHP is an "interpreted" language and not a "compiled" languages like Java and C#. It means the source code is executed/interpreted during run time as per request.


Comments

// single line comment

/*
 multiple line of comment
*/

 

in this module we will discuss about variable in PHP such as variable type and naming convention

Defining Variables

  • A variable must start with '$' notation, i.e $name = 'Azman'. 
  • The naming convention for variables includes:
    • must start with a character and follow by a number
    • no special character except "_" (underscore)
  • The variable is case sensitive
<?php
$name = 'Azman'; // valid
$_name = 'John Doe'; // valid
$20_name = 20; // not valid
$*name = '...'; // no valid


Data Types

PHP supports the following data types:

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource


Integer Type

<?php
$x = 100;
$y = 200;
$z = $x + $y;
echo "$x + $y = $z";


Floating-Point Type

<?php
$x = 20.5
$y = 11.3;
$z = $x + $y;
echo "$x + $y = $z";


Bool Type

<?php
$x = true;
$y = false;


Null Type

<?php
$x = null;
var_dump($x);


Default Values

Variables that are declared without a value and undefined/undeclared variables are null by default

Arithmetic Operators

Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power


Assignment Operators

Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus


Combined Assignment Operators

<?php
$a = 1; // basic assignment
echo ($a += 2) . "\n"; // read as '$a = $a + 2'; $a now is (1 + 2) => 3
echo ($a -= 1) . "\n"; // $a now is (3 - 1) => 2
echo ($a *= 2) . "\n"; // $a now is (2 * 2) => 4
echo ($a /= 2) . "\n"; // $a now is (4 / 2) => 2
echo ($a %= 5) . "\n"; // $a now is (2 % 5) => 2 (modulus or remainder)


Increment and Decrement Operators

Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one


Comparison Operators

Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.


Logical Operators

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true


Operator Precedence

Operators
()
new
[]
! ~ ++ -- (int) (double) (string) (array) (object)
* / %
+ - .
<< >>
< <= > >=
== != === !===
&
^
|
&&
||
?   :
= += -= *= /= .= %= |= ^= ~= <<= >>=
print
and
xor
or
,


Additional Logical Operators

Operator Name Example Result
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.
Introduced in PHP 7

 

 

String Concatenation

<?php
$a = "hello";
$b = "world";
$c = $a . " " . $b;
echo $c; // hello world

$d = "welcome to PHP training ";
$d .= $c
echo $d;


Delimiting Strings

<?php
$string = "123,46,78,000";
$str_arr = explode (",", $string); 
print_r($str_arr);


Heredoc Strings

<?php
$foo = 'bar';
echo <<<EOT
Hello $foo
Goodbye!
EOT;


Nowdoc Strings

<?php
$foo = 'bar';
echo <<<'EOT'
Hello $foo
Goodbye!
EOT;


Escape Characters

<?php
$name = 'Azman';
echo 'My name is \'$name\'';


Character Reference

Using the decimal values 43 and 61 to add the ASCII Characters: + and =.

<?php
$str = chr(43);
$str2 = chr(61);
echo("2 $str 2 $str2 4");


String Compare

<?php 
$name1 = "Geeks"; 
$name2 = "Geeks"; 
  
// Use == operator 
if ($name1 == $name2) { 
    echo 'Both strings are equal'; 
} else { 
    echo 'Both strings are not equal'; 
} 

 

An array stores multiple values in one single variable

 

Numeric Arrays

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>


Associative Arrays

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


Mixed Arrays

<?php

$student = [
  ['name' => 'Azman', 'ic' => 1234],
  ['name' => 'John Doe', 'ic' => 5678]
];


Multi-Dimensional Arrays

<?php
// Define a multidimensional array
$contacts = array(
    array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
    ),
    array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
    ),
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>

 

If Statement

<?php
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
}
?>


Switch Statement

<?php
$favcolor = "red";

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


Alternative Syntax

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>


Mixed Modes

 


Ternary Operator

<?php
$marks = 40;
print ($marks >= 40) ? "pass" : "Fail";

 

While Loop

<?php
$x = 1;

while($x <= 5) {
  echo "The number is: $x <br>";
  $x++;
}
?>


Do-while Loop

<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>


For Loop

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


Foreach Loop

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
?>


Alternative Syntax

<?php
$colors = array( "red", "green", "blue", "orange" );
?>
 
Pick a color:
<select>
<?php foreach( $colors as $value ): ?>
  <option><?php echo $value?></option>
<?php endforeach ?>
</select>


Break

<?php
for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    break;
  }
}


Continue

<?php
$stack = array('first', 'second', 'third', 'fourth', 'fifth');

foreach($stack as $v){
    if($v == 'second') {
      continue;
    }
    echo $v.'<br>';
}

 

Functions are blocks of code that can be executed to do something.

Defining Functions

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


Calling Functions

<?php
writeMsg(); // call the function


Function Parameters

// functions require 'function' keyword
// separate the parameters with a comma
function addFunction($num1, $num2) {
	$sum = $num1 + $num2;
	echo "Sum of the two numbers is : $sum";
}

addFunction(1, 2); // echoes: Sum of the two numbers is : 3


Default Parameters

function foo($blah, $x = null, $y = null) {
    if (null === $x) {
        $x = "some value";
    }

    if (null === $y) {
        $y = "some other value";
    }
}


Variable Parameter Lists

To use variable length parameters on PHP you need the function func_get_args() instead to define the parameters on function declaration. Your function look like this

<?php
function foo()
{
    $params_count = func_num_args();
    $params_values = func_get_args();
}


Return Statement

<?php
function getXYZ()
{
    return array(4,5,6);
}


Scope and Lifetime

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.

<?php
$x = 5; // global scope

function myTest() {
  // using x inside this function will generate an error
  echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";

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

<?php
function myTest() {
  $x = 5; // local scope
  echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>


Anonymous Functions

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

<?php
$multiply = function ($x, $y) {
  return $x * $y;
};

echo $multiply(10, 20);


Closures

Same as anonymous

<?php
$message = 'Hi';
$say = function () {
  echo $message;
};

$say();

PHP issued the following notice: 

Undefined variable: message in ...

<?php
$message = 'Hi';
$say = function () use ($message) {
  echo $message;
};

$say();


Generators

<?php
foreach (range(1, 9, 2) as $number) {
    echo "$number ";
}


Built-in Functions

Built-in functions are those functions that are already readymade. These functions are used for a specific purpose. Each built-in function has different functionalities. These built-in functions are used only on the basis of their functionality. Many built-in functions are available in PHP.

<?php 
$str="This is a simple example of printf";
$res1=strlen($str);
$res2=str_word_count($str);
printf("Your string lenght is  %d. You string words count: %d",$res1,$res2);
?>

 

OOP is a coding methodology / style. It's made our code more modular, reusable, and easy to maintain. It also makes it easy to debug when things goes wrong.

The 4 Principles Of Object-Oriented Programming. Also known as the 'four pillars of OOP'.

  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritance.

A class is a template for objects, and an object is an instance of a class. 

Instantiating an Object

<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }

  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit();
$banana = new Fruit();
?>


Accessing Object Members

$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();


Initial Property Values

<?php
class Fruit {
  // Properties
  public $name = 'Jambu batu';
  public $color = 'Hijau';


Constructor

A constructor allows you to initialize an object's properties upon the creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit("Apple");
echo $apple->get_name();
?>


Destructor

A destructor is called when the object is destructed or the script is stopped or exited.

<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name) {
    $this->name = $name;
  }
  function __destruct() {
    echo "The fruit is {$this->name}.";
  }
}

$apple = new Fruit("Apple");
?>


Case Sensitivity

  • The class keyword is case insensitive
  • Class names are case insensitive, for declaration, instantiation, and static calls
  • Class methods, being functions, are case insensitive
  • Class properties, being variables & constants, are case sensitive


Object Comparison

to compare objects in PHP using the comparison operator ( ==) and identity operator (===). 

When you use the identity operator (===) to compare objects, they are identical if and only if both of them reference the same instance of a class.

<?php
require 'Point.php';

$p1 = new Point(10, 20);
$p2 = new Point(10, 20);

if ($p1 == $p2) {
	echo 'p1 and p2 are equal.';
} else {
	echo 'p1 and p2 are not equal.';
}
<?php
require 'Point.php';

$p1 = new Point(10, 20);
$p2 = $p1;

if ($p1 === $p2) {
	echo 'p1 and p2 are identical.';
} else {
	echo 'p1 and p2 are not identical.';
}

$p3 = new Point(10, 20);
if ($p1 === $p3) {
	echo 'p1 and p3 are identical.';
} else {
	echo 'p1 and p3 are not identical.';
}


Anonymous Classes

 an anonymous class is one that doesn't have a name. It is meant for one-time use, and if one needs to define a class on the fly

<?php
$obj=new class {
   public function sayhello(){
      echo "Hello World";
   }
};
$obj->sayhello();
?>


Closure Object

Same as an anonymous class

Inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.

An inherited class is defined by using the extends keyword.

<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  public function intro() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
  }
}

// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
  public function message() {
    echo "Am I a fruit or a berry? ";
  }
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

Overriding Members

Inherited methods can be overridden by redefining the methods (use the same name) in the child class.

Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):

<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  public function intro() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
  }
}

class Strawberry extends Fruit {
  public $weight;
  public function __construct($name, $color, $weight) {
    $this->name = $name;
    $this->color = $color;
    $this->weight = $weight;
  }
  public function intro() {
    echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram.";
  }
}

$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?>


Final Keyword

The final keyword can be used to prevent class inheritance or to prevent method overriding.

The following example shows how to prevent class inheritance

<?php
final class Fruit {
  // some code
}

// will result in error
class Strawberry extends Fruit {
  // some code
}
?>
<?php
class Fruit {
  final public function intro() {
    // some code
  }
}

class Strawberry extends Fruit {
  // will result in error
  public function intro() {
    // some code
  }
}
?>


Instance of Operator

Check whether an object belongs to a specific class.

<?php
class MyClass {}
class AnotherClass extends MyClass{}
$obj = new AnotherClass();

if($obj instanceof AnotherClass) {
  echo "The object is AnotherClass";
}

// The object is also an instance of the class it is derived from
if($obj instanceof MyClass) {
  echo "The object is MyClass<br>";
}
?>

 

 

<?php
class Fruit {
  public $name;
  protected $color;
  private $weight;
}

$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

The following example showing a better approach to using the encapsulation method. In this method, all properties are hidden and can bet set or get only using the public method of setter and getter.

<?php
class Fruit {
  private $name;
  private $color;
  private $weight;

  function setName($n) {  // a public function (default)
    $this->name = $n;
  }

  public function setColor($n) { // a protected function
    $this->color = $n;
  }

  public function setWeight($n) { // a private function
    $this->weight = $n;
  }
}

$mango = new Fruit();
$mango->setName('Mango');
$mango->setColor('Yellow');
$mango->setWeight('300');

 

Private Access

private - the property or method can ONLY be accessed within the class


Protected Access

protected - the property or method can be accessed within the class and by classes derived from that class


Public Access

public - the property or method can be accessed from everywhere. This is default


Var Keyword

The var keyword in PHP is used to declare a property or variable of class that is public by default. The var keyword is the same as public when declaring variables or properties of a class. Note: The var keyword was deprecated from version 5.0.


Object Access

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.


Access Level Guideline

If you don't use any visibility modifier, the property / method will be public. it's a good idea to make most of the property private and use the setter and getter method to set and get value. This is to prevent unnecessary changes of data by outside programs.

 

 

Referencing Static Members

Static methods can be called directly - without creating an instance of the class first. Static methods are declared with the static keyword

<?php
class Greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// Call static method
greeting::welcome();
?>

Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).


Static Variables

Static properties can be called directly - without creating an instance of a class. Static properties are declared with the static keyword.
A class can have both static and non-static properties. A static property can be accessed from a method in the same class using the self keyword and double colon (::)

<?php
class pi {
  public static $value = 3.14159;

  public function staticValue() {
    return self::$value;
  }
}

// Get static property
echo pi::$value;

$pi = new pi();
echo $pi->staticValue();
?>


Late Static Bindings

 

 

 

Constant Guideline

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

To create a constant, use the define() function.

<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>

Constants are automatically global and can be used across the entire script.

<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
  echo GREETING;
}
 
myTest();
?>


Magic Constants

There are nine magic constants in PHP. In which eight magic constants start and end with double underscores (__).

__LINE__
__FILE__
__DIR__
__FUNCTION__
__CLASS__
__TRAIT__
__METHOD__
__NAMESPACE__
ClassName::class

 

 

Interfaces allow you to specify what methods a class should implement. Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".

Interfaces are declared with the interface keyword

 

Interface Signatures

<?php
interface InterfaceName {
  public function someMethod1();
  public function someMethod2($name, $color);
  public function someMethod3() : string;
}
?>


Interface Example

<?php
interface Animal {
  public function makeSound();
}

class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}

$animal = new Cat();
$animal->makeSound();
?>


Interface Usages

Why should you use PHP interfaces?

  • An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.
  • An interface enables you to model multiple inheritances because a class can implement more than one interface.
  • By implementing an interface, the object’s caller needs to care only about the object’s interface, not implementations of the object’s methods. Therefore you can change the implementations without affecting the caller of the interface.
  • An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.
  • An interface enables you to model multiple inheritances because a class can implement more than one interface.


Interface Guideline

  • A class can inherit from one class only. However, it can implement multiple interfaces.
  • To define a class that implements an interface, you use the implements keyword
  • When a class implements an interface, it’s called a concrete class. The concrete class needs to implement all the methods of the interface.
  • Like a class, an interface can extend another interface using the extends keyword

 

 

Abstract Methods

  • Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks.
  • An abstract class is a class that contains at least one abstract method.
  • An abstract method is a method that is declared but not implemented in the code.

An abstract class or method is defined with the abstract keyword:

<?php
abstract class ParentClass {
  abstract public function someMethod1();
  abstract public function someMethod2($name, $color);
  abstract public function someMethod3() : string;
}
?>


Abstract Example

<?php
// Parent class
abstract class Car {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  abstract public function intro() : string;
}

// Child classes
class Audi extends Car {
  public function intro() : string {
    return "Choose German quality! I'm an $this->name!";
  }
}

class Volvo extends Car {
  public function intro() : string {
    return "Proud to be Swedish! I'm a $this->name!";
  }
}

class Citroen extends Car {
  public function intro() : string {
    return "French extravagance! I'm a $this->name!";
  }
}

// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->intro();
echo "<br>";

$volvo = new volvo("Volvo");
echo $volvo->intro();
echo "<br>";

$citroen = new citroen("Citroen");
echo $citroen->intro();
?>


Abstract Classes and Interfaces

Interface Abstract Class
Interface support multiple inheritance Abstract class does not support multiple inheritance
Interface doesn't contains data member Abstract class contain data member
Interface doesn't contain constructor Abstract contains constructor
An interface cannot have access modifiers by default everything is assumed as public Ab abstract class can contain access modifiers for the subs, functions, properties
Member of interface cannot be static Only complete member of abstract class can be static


Abstract Guideline

  •  we need to prefix the name of the class with the abstract keyword.
  • We put the abstract methods that are also declared with the abstract keyword within the abstract class
  • Once we have an abstract method in a class, the class must also be abstract
  • An abstract class can have non abstract methods. In fact, it can even have properties, and properties couldn't be abstract.
  • we cannot create objects from abstract classes, we need to create child classes that inherit the abstract class code.

 

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

<?php
trait TraitName {
  // some code...
}
?>
<?php
class MyClass {
  use TraitName;
}
?>
<?php
trait message1 {
  public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>

 

Inheritance and Traits

Traits are used to solve the fact that PHP doesn't support multiple inheritance.

 

Trait Guidelines

  • Traits are declared with the trait keyword
  • Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected)
  • To use a trait in a class, use the use keyword

 

The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website. There is one big difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute

 

Include Path

<?php
include 'filename';

Assume we have a standard footer file called "footer.php", that looks like this.

<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " jomdemy.com</p>";
?>
<html>
<body>
  <h1>Welcome to my home page!</h1>
  <p>Some text.</p>
  <p>Some more text.</p>
  <?php include 'footer.php';?>
</body>
</html>


Require

<?php
require 'filename';


Include_once

The include_once keyword is used to embed PHP code from another file. If the file is not found, a warning is shown and the program continues to run. If the file was already included previously, this statement will not include it again.

<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include_once 'footer.php';?>

</body>
</html>


Require_once

Require_once is ignored if the required file has already been added by any of the include statements.

<?php 
require_once 'require_oncefile.php';
?>


Return

This is one of those little-known features of PHP, but it can be kind of nice for setting up really simple config files

includeme.txt

$x = 5;
return $x;

main.php

$myX = require 'includeme.php'; 


_Autoload

It's a magic function that helps you include/require files using the class names.

function __autoload($class_name) 
{
    require_once $DOCUMENT_ROOT . '/classes/' . $class_name . '.php';
}

 

Since PHP 5 you can use type hinting to specify the expected data type of an argument in a function declaration. When you call the function, PHP will check whether or not the arguments are of the specified type. If not, the run-time will raise an error and execution will be halted.

 

Argument Type Declarations

<?php
function enroll(Student $student, School $school) {
  echo "Enrolling " . $student->name . " in " . $school->name;
}


Return Type Declarations

In PHP 7, a new feature, Return type declarations have been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
  return $value;
}
print(returnIntValue(5));
?>


Strict Typing

"Strict types" mode only checks types at specific points in the code; it does not track everything that happens to the variable.

The meaning of "Casting" is taking a variable of one particular data type and converting it to another data type. (ex: Integer to Float). in PHP, we do not need to specify the data type of the variable when we declare it. PHP parser automatically set it for us. But, the data type of the variable can be converted to another one automatically or manually. This is called Type Casting.

Explicit Casts

By placing the type name in parentheses in front of a variable, PHP converts the value to the desired type:

  • Cast to integer. (int) $var or (integer) $var.
  • Cast to Boolean. (bool) $var or (boolean) $var.
  • Cast to float. (float) $var , (double) $var or (real) $var.
  • Cast to string. (string) $var.
  • Cast to array. ...
  • Cast to object.
<?php
$x = 5.35;
$y = (int) $x; // cast $x to integer
var_dump($y);

Immplicit Casts

Implicit casting is something done by PHP according to your code, but you are not capable of customizing. When dividing an integer by another integer the result can either be integer or float. The decision is taken by PHP. See the below example.

<?php
$x = 2; 
$y = 4;

var_dump($x / $y); // 2/4 = 0.5 (Float)
var_dump($y / $x); // 4/2 = 2 (Int)


Set type

Set the type of variable var to type.

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?>


Get type

Get the type of a variable

<?php
$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}
?>

The above example will output something similar to:

integer
double
NULL
object
string

This module will discuss frequently used function used to test a variable.

Isset

  • The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL.
  • This function returns true if the variable exists and is not NULL, otherwise, it returns false.
<?php
$a = 0;
// True because $a is set
if (isset($a)) {
  echo 
  "Variable 'a' is set.<br>";
}

$b = null;
// False because $b is NULL
if (isset($b)) {
  echo "Variable 'b' is set.";
}
?>


Empty

  • Determine whether a variable is considered to be empty.
  • A variable is considered empty if it does not exist or if its value equals false (is a falsey).
<?php
empty('');      // true
empty('0');     // true
empty(0);       // true
empty(null);    // true
empty([]);      // true
empty(false);   // true
empty('false'); // false
empty('true');  // false


Is_null

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

<?php
$var = NULL;  
if (is_null($var)) {
  echo "yes, is null";
} else {
  echo "not null";
}
?>


Unset

Destroy a variable

<?php
$a = "Hello world!";
echo "The value of variable 'a' before unset: " . $a . "<br>";
unset($a);
echo "The value of variable 'a' after unset: " . $a;
?>


Null Coalescing Operator

The null coalescing operator (??) is used to replace the ternary operation in conjunction with isset() function and returns its first operand if it exists and is NOT NULL; otherwise it returns its second operand.

<?php
$username = $_GET['username'] ?? 'not passed';

// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';


Determining Types

The gettype() return the type of different variables:

<?php
$a = 3;
echo gettype($a) . "<br>";

$b = 3.2;
echo gettype($b) . "<br>";

$c = "Hello";
echo gettype($c) . "<br>";

$d = array();
echo gettype($d) . "<br>";

$e = array("red", "green", "blue");
echo gettype($e) . "<br>";

$f = NULL;
echo gettype($f) . "<br>";

$g = false;
echo gettype($g) . "<br>";
?>


Variable Information

var_dump() is used to dumps information about a variable.

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

 

 

Property Overloading

PHP property overloading is used to create dynamic properties in the object context. For creating these properties no separate line of code is needed. A property associated with a class instance, and if it is not declared within the scope of the class, it is considered as overloaded property.

Property overloading allows you to seamlessly obscure from the user the actual location of your object's properties and the data structure you use to store them.

<?php
class PropertyTest
{
    private $data = array();

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
       return $this->data[$name];
    }
}

$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n\n";
?>


Method Overloading

It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike property overloading, PHP method overloading allows function call on both object and static context.

<?php
function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
    }
}

/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/
myFunc('a', 2, 3.5);


Isset and unset Overloading

 

 

Magic methods are special methods which override PHP's default's action when certain actions are performed on an object.

_ToString

The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print.


_Invoke

The __invoke() method is called when a script tries to call an object as a function.

<?php
class CallableClass
{
    public function __invoke($x)
    {
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>


Object Serialization

serialize() checks if the class has a function with the magic name __serialize(). If so, that function is executed prior to any serialization. It must construct and return an associative array of key/value pairs that represent the serialized form of the object. If no array is returned a TypeError will be thrown.

    public function __serialize(): array
    {
        return [
          'dsn' => $this->dsn,
          'user' => $this->username,
          'pass' => $this->password,
        ];
    }


_Sleep

 


_Wakeup

 


Set State

 


Object Cloning

 

The PHP superglobals $_GET and $_POST are used to collect form-data.

HTML Form

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>


Sending with POST

<form action="welcome.php" method="post">
...
</form>


Sending with GET

<form action="welcome.php" method="get">
...
</form>


Request Array

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>


Security Concerns

There few security that need to be done before saving data into database.

  • SQL Vulnerabilities. SQL injection is the most commonly reported security issue.
  • Buffer Overflows. Usually, a buffer overflow problem is not caused directly by the code of interpreted languages like PHP.
  • XSS Exploits.
  • Error Handling Problems.
  • Remote Administration Flaws.
  • Session And Cookie Hijacking.


Submitting Arrays

<form method="post">
  <input name="favorites[]" type="text"/>
  <input name="favorites[]" type="text"/>
  <input type="submit" value="Go"/>
</form>


File Uploading

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>


Superglobals

Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in all scopes.

Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

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

Namespaces are qualifiers that solve two different problems:

  • They allow for a better organization by grouping classes that work together to perform a task
  • They allow the same name to be used for more than one class
  • A namespace is used to avoid conflicting definitions 

For example, you may have a set of classes that describe an HTML table, such as Table, Row, and Cell while also having another set of classes to describe furniture, such as Table, Chair, and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.

Creating Namespaces

Declare a namespace called Html:

namespace Html;

Note: A namespace declaration must be the first thing in the PHP file. The following code would be invalid:

<?php
echo "Hello World!";
namespace Html;
...
?>
<?php
namespace Html;
class Table {
  public $title = "";
  public $numRows = 0;
  public function message() {
    echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
  }
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>

<!DOCTYPE html>
<html>
<body>

<?php
$table->message();
?>

</body>
</html>


Nested Namespaces

Declare a namespace called Html inside a namespace called Code:

namespace Code\Html;

Use classes from the Html namespace:

<?php
$table = new Html\Table()
$row = new Html\Row();


Alternative Syntax

<?php
namespace MyProject {
  const CONNECT_OK = 1;
  class Connection { /* ... */ }
  function connect() { /* ... */  }
}

namespace { // global code
  session_start();
  $a = MyProject\connect();
  echo MyProject\Connection::start();
}
?>


Referencing Namespaces

namespace Acme\Tools;
class Foo
{
}
require 'Foo.php';
$foo = new \Acme\Tools\Foo();


Namespace Aliases

It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword:

use Html as H;
$table = new H\Table();


Namespace Keyword

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.

<?php
namespace MyProject;

echo '"', __NAMESPACE__, '"'; // outputs "MyProject"
?>


Namespace Guideline

  • Multiple namespaces can be declared within a single PHP code.

In this module we will learn three ways of working with PHP and MySQL:

  • MySQLi (object-oriented)
  • MySQLi (procedural)
  • PDO

Setting Up the Database Connection

Example (MySQLi OOP)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Example PDO

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
  $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>

Initializing all Includes in one file

<?php
include 'connection.php';
...


Init file inclusion reminder

 


Creating the Database Class

<?php
class DataBase {
	public $conn;
	public $queryCount = 0;
	
	public function __construct()
	{
		$this->conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
		mysqli_select_db($this->conn, DB_NAME);
		mysqli_set_charset($this->conn, 'utf8');
	}
}


Future Update for database class

Many more function to can be included into the class such as:

  • query
  • count
  • escape
  • lastId
  • insert
  • execute
  • select


Automatic DB Connection Setup

 


The Query Method

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
  }
} else {
  echo "0 results";
}


Database Class Helper Methods

public function lastId()
{
  return mysqli_insert_id($this->conn);
}


Testing Query Method

    public function query($query)
	{
		$this->queryCount++;
		$this->queries[] = $query;
		
		$result = mysqli_query($this->conn, $query);
		
		if ($result === false) {
			$this->debug($query);
		}
		
		if (mysqli_num_rows($result) == 0) {
			return array();
		}
		
		$salida = array();
		while ($row = mysqli_fetch_assoc($result)) {
			$salida[] = $row;
		}

		mysqli_free_result($result);
		return $salida;
	}


Improving our Connection to be more OOP

 

 

Develop a simple application which demonstrates all PHP features

Table

CREATE TABLE IF NOT EXISTS `event` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `descr` text,
  `event_dt` date DEFAULT NULL,
  `status` char(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `event_members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) NOT NULL,
  `user_id` varchar(15) NOT NULL,
  `is_attend` char(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `user` (
  `user_id` varchar(15) NOT NULL,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `role` varchar(10) NOT NULL,
  `password` varchar(100) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 


Login

 


Authorization

 


Create, Retrieve, Update, Delete (CRUD)

 


Pagination


Layout / template management

 

 

Continuation from workshop 1

 


Session

 


Upload / download

 


Audit trail

 


Fail and folder management (create, copy, rename, delete, list)

 


Pdf, Excel generation

 


Twitter Bootstrap 5 integration

 


More CRUD sample

 


Conclusion and closing

 

ctl + / = toggle comment

ctl + s = save, ctl + v = paste, cl + c = copy

ctl + b = toggle project explorer

ctl + d = search similar

shift + alt + arrow up / down = move a line up / down

ctl + x = cut a line

F11 = full window / zen mode

shift + ctl + k s = save all

 

htmlentities() vs htmlspecialchars() Function in PHP
 

htmlentities() Function

The htmlentities() function is an inbuilt function in PHP which is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entity.

Syntax

string htmlentities( $string, $flags, $encoding, $double_encode )
Parameters: This function accepts four parameters as mentioned above and described below:

  • $string: This parameter is used to hold the input string.
  • $flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes.
  • $encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version.
  • $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything.

Return Values: This function returns the string which has been encoded.

<?php
// String convertable to htmlentities 
$str = '<a href="https://www.geeksforgeeks.org">GeeksforGeeks</a>';
  
// It will convert htmlentities and print them
echo htmlentities( $str );

Output : &lt;a href=&quot;https://www.geeksforgeeks.org&quot;&gt;GeeksforGeeks&lt;/a&gt;

 

htmlspecialchars() Function

The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities.

Syntax:

string htmlspecialchars( $string, $flags, $encoding, $double_encode )
  • $string: This parameter is used to hold the input string.
  • $flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes.
  • $encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version.
  • $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything.

Return Values: This function returns the converted string. If there is invalid input string then empty string will returned.

<?php
// Example of htmlspecialchars() function
// String to be converted
$str = '"geeksforgeeks.org" Go to GeeksforGeeks';
// Converts double and single quotes
echo htmlspecialchars($str, ENT_QUOTES); 

Output : &quot;geeksforgeeks.org&quot; Go to GeeksforGeeks

 

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is:

  • htmlspecialchars() function convert the special characters to HTML entities.
  • htmlentities() function convert all applicable characters to HTML entities.
     

Quiz

Log in with the account you registered for this training to take its quizzes.

Quiz asas PHP

Kuiz ini akan menguji anda asas PHP seperti definiasi variable, operator, function dan loop

15 questions

Borang Penilaian Keberkesanan Latihan

Training evaluation ยท PHP Beginner / Intermediate

Log in with the account you registered for this training to fill in the survey.

Log in to fill in the survey

Attendance

Registration closed
This training ended on 3 Aug 2021, so new attendance can no longer be registered.

Students (17)

# Name
1. Zaidar bt Osman
2. Jannaltul Firdaus Azmi
3. ZURAIDAH TENGKIS
4. SAIFUL AZRI BIN MOHAMAD
5. NOR ADILA BT ABD RAHIM
6. MOHD REDZUAN BIN MOHAMED
7. MAIZAN BINTI SULAIMAN
8. NUR NAZIHAH BINTI ABDUL RASHID
9. NIK AZLISHAM FAZLI BIN NIK AZMI
10. Fateen Nadia bt Ab Malek
11. ZURINA BINTI ABDUL RAHMAN
12. Mohamad Fikri Bin Ramlan
13. Budi Hermawan Bin Saka
14. Nur Hidayah Bte Osman
15. Syed Abdullah bin Sayed Abu Bakar
16. Marita Binti Manaf
17. MAIZAN BINTI SULAIMAN