Category: Advanced

  • Special Types

    PHPs two data types resource and NULL are classified as special types. An object of resource type refers to external resources like database connection, file streams etc. On the other hand, a NULL data type is a variable without any data assigned to it. In this chapter, we shall learn more about these types.

    Resource Type

    A PHP program often needs to interact with an external environment such as a database, or a disk file etc. These are treated as resources in PHP. Resource is a special data type that refers to any such external resource. PHP uses relevant functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable.

    PHP’s Zend engine uses reference counting system. Hence, a resource with zero reference count is destroyed automatically by garbage collector and the memory used by resource data type need not be freed manually.

    Different built-in PHP functions return respective resource variables. Subsequently, PHP uses them for interacting with the corresponding external environment. For example, the fopen() function returns a file resource, which acts as a file handle and the read/write operations on the file are facilitated by this resource variable.

    The following table summarizes different functions that return resource variables −

    Resource TypeBuilt-in functionsDefinition
    ProducedSold
    bzip2bzopen()bzclose()Bzip2 file
    curlcurl_init()curl_close()Curl session
    ftpftp_connect(),ftp_close()FTP stream
    mssql linkmssql_connect()mssql_close()Link to Microsoft SQL Server database
    mysql linkmysql_connect()mysql_close()Link to MySQL database
    mysql resultmysql_db_query(),mysql_free_result()MySQL result
    oci8 connectionoci_connect()oci_close()Connection to Oracle Database
    ODBC linkodbc_connect()odbc_close()Link to ODBC database
    pdf documentpdf_new()pdf_close()PDF document
    streamopendir()closedir()Dir handle
    streamfopen(), tmpfile()fclose()File handle
    socketsocket_create()Socket_close()Socket handle
    xmlxml_parser_create()xml_parser_free()XML parser
    zlibgzopen()gzclose()gz-compressed file
    zlib.deflatedeflate_init()None()incremental deflate context
    zlib.inflateinflate_init()None()incremental inflate context

    PHP has get_resource_type() function that returns resource type of a variable.

    get_resource_type(resource$handle):string

    where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type.

    There is also get_resource_id() function an integer identifier for the given resource.

    get_resource_id(resource$resource):int

    Example

    This function provides a type-safe way for generating the integer identifier for a given resource.

    <?php
       $fp = fopen("hello.php", "r");
       $resource = get_resource_type($fp);
       $id = get_resource_id($fp);
       echo "The resource type is : $resource The resource ID is : $id";
    ?>

    It will produce the following output −

    The resource type is : stream The resource ID is : 5
    

    NULL type

    In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function.

    $var=NULL;

    It is possible to cast variable of other type to null, although casting null to other type has been deprecated from PHP 7.2. In earlier versions, casting was done using (unset)$var syntax

    Example

    The following example shows how to assign NULL to a variable

    <?php
       $var=NULL;
       var_dump($var);
    ?>

    It will produce the following output −

    NULL
    

    Example

    The following example performs null variable to other primary variables −

    <?php
       $var = NULL;
       var_dump( (int)   $var);
       var_dump((float)$var);
       var_dump((bool)  $var) ;
       var_dump( (boolean) $var);
    ?>

    It will produce the following output −

    int(0)
    float(0)
    bool(false)
    bool(false)
    
  • Exceptions

    Prior to version 7, PHP parser used to report errors in response to various conditions. Each error used to be of a certain predefined type. PHP7 has changed the mechanism of error reporting. Instead of traditional error reporting, most errors are now reported by throwing error exceptions.

    The exception handling mechanism in PHP is similar to many other languages, and is implemented with the try, catch, throw and finally keywords.

    The Throwable Interface

    Exceptions in PHP implements the Throwable interface. The Throwable interface acts as the base for any object that can be thrown via throw statement, including Error and Exception objects.

    A user defined class cannot implement Throwable interface directly. Instead, to declare a user defined exception class, it must extend the Exception class.

    PHP code with potential exceptions is surrounded in a try block. An exception object is thrown if it is found, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block. Moreover, there may be more than one catch/finally blocks corresponding to a try block.

    try{// throw errors in the try-block // if an error occurs we can throw an exceptionthrownewException('this is an error.');}catch(Exception$e){// catch the throws in the catch-block // do something with the exception object, eg.  // display its messageecho'Error message: '.$e->getMessage();}

    If an exception is thrown and there is no catch block, the exception will “bubble up” until it finds a matching catch block. If the call stack is unwound all the way to the global scope without encountering a matching catch block, a global exception handler will be called (if it is set) otherwise the program will terminate with a fatal error.

    set_exception_handler

    This function sets the default exception handler if an exception is not caught within a try/catch block. After the callback is executed, the program execution will stop.

    set_exception_handler(?callable$callback):?callable

    The $callback parameter is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

    The function returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

    Example

    Take a look at the following example −

    <?php
       function handler($ex) {
    
      echo "Uncaught exception is : " , $ex-&gt;getMessage(), "\n";
    } set_exception_handler('handler'); throw new Exception('Not Found Exception'); echo "not included Executed\n"; ?>

    It will produce the following output −

    Uncaught exception is : Not Found Exception
    

    SPL Exceptions

    Standard PHP library contains predefined exceptions −

    Sr.NoPredefined Exceptions
    1LogicExceptionException that represents error in the program logic.
    2BadFunctionCallExceptionException thrown if a callback refers to an undefined function or if some arguments are missing.
    3BadMethodCallExceptionException thrown if a callback refers to an undefined method or if some arguments are missing.
    4DomainExceptionException thrown if a value does not adhere to a defined valid data domain.
    5InvalidArgumentExceptionException thrown if an argument is not of the expected type.
    6LengthExceptionException thrown if a length is invalid.
    7OutOfRangeExceptionException thrown when an illegal index was requested.
    8RuntimeExceptionException thrown if an error which can only be found on runtime occurs.
    9OutOfBoundsExceptionException thrown if a value is not a valid key.
    10OverflowExceptionException thrown when adding an element to a full container.
    11RangeExceptionException thrown to indicate range errors during program execution. An arithmetic error other than under/overflow.
    12UnderflowExceptionException thrown when performing an invalid operation on an empty container, such as removing an element.
    13UnexpectedValueExceptionException thrown if a value does not match with a set of values.

    User-defined Exception

    You can define a custom exception class that extends the base Exception class. Following script defines a custom exception class called myException. This type of exception is thrown if value of $num is less than 0 or greater than 100.

    Example

    The getMessage() method of Exception class returns the error message and getLine() method returns line of code in which exception appears.

    <?php
       class myException extends Exception {
    
      function message() {
         return "error : ". $this-&gt;getMessage(). "in line no". $this-&gt;getLine();
      }
    } $num=125; try {
      if ($num&gt;100 || $num&lt;0)
      throw new myException("$num is invalid number");
      else
      echo "$num is a valid number";
    } catch (myException $m) {
      echo $m-&gt;message();
    } ?>

    Run the above code with $num=125 and $num=90 to get an error message and a message of valid number −

    error : 125 is invalid number in line no 10
  • JSON

    Standard distributions of PHP have the JSON support enabled by default. The PHP extension implements the JavaScript Object Notation (JSON) data interchange format. The JSON extension in PHP parser handles the JSON data.

    JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data interchange format. JSON defines a small set of formatting rules for the portable representation of structured data. It is a text based data format that is easy for the humans as well as machines to read.

    The JSON extension in PHP version 5.2 onwards provides a number of predefined constants, JSON related functions, and also a JsonException class.

    PHP JSON Functions

    PHP has the following JSON functions −

    json_encode()

    This function returns a string containing the JSON representation of the supplied value. If the parameter is an array or object, it will be serialized recursively.

    json_encode(mixed$value,int$flags=0,int$depth=512):string|false

    json_decode()

    This function takes a JSON encoded string and converts it into a PHP value.

    json_decode(string$json,?bool$associative=null,int$depth=512,int$flags=0):mixed

    When the associative parameter of this function is true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects.

    The encode/decode operations are affected by the supplied flags. The predefined constants and their integer values are as below −

    Predefined ConstantValues
    JSON_HEX_TAG1
    JSON_HEX_AMP2
    JSON_HEX_APOS4
    JSON_HEX_QUOT8
    JSON_FORCE_OBJECT16
    JSON_NUMERIC_CHECK32
    JSON_UNESCAPED_SLASHES64
    JSON_PRETTY_PRINT128
    JSON_UNESCAPED_UNICODE256

    json_last_error_msg()

    This function returns the error string of the last json_encode() or json_decode() call.

    json_last_error_msg():string

    “No error” message is returned if no error has occurred.

    json_last_error()

    This function returns an integer.

    json_last_error():int

    The function returns an integer corresponding to one of the following constants −

    Sr.NoConstant & Meaning
    1JSON_ERROR_NONENo error has occurred
    2JSON_ERROR_DEPTHThe maximum stack depth has been exceeded
    3JSON_ERROR_STATE_MISMATCHInvalid or malformed JSON
    4JSON_ERROR_CTRL_CHARControl character error, possibly incorrectly encoded
    5JSON_ERROR_SYNTAXSyntax error
    6JSON_ERROR_UTF8Malformed UTF-8 characters, possibly incorrectly encoded
    7JSON_ERROR_RECURSIONOne or more recursive references in the value to be encoded
    8JSON_ERROR_INF_OR_NANOne or more NAN or INF values in the value to be encoded
    9JSON_ERROR_UNSUPPORTED_TYPEA value of a type that cannot be encoded was given
    10JSON_ERROR_INVALID_PROPERTY_NAMEA property name that cannot be encoded was given
    11JSON_ERROR_UTF16Malformed UTF-16 characters, possibly incorrectly encoded

    Example

    The following PHP code encodes a given array to JSON representation, and decodes the JSON string back to PHP array.

    <?php
       $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
       $encoded = json_encode($arr);
       echo "The initial array: " . PHP_EOL;
       var_dump($arr);
       echo "Encoded JSON: $encoded" . PHP_EOL;
    
       $decoded = json_decode($encoded);
       echo "Array obtained after decoding: " . PHP_EOL;
       var_dump($decoded);
    ?>

    It will produce the following output −

    The initial array: 
    array(5) {
       ["a"]=>
       int(1)
       ["b"]=>
       int(2)
       ["c"]=>
       int(3)
       ["d"]=>
       int(4)
       ["e"]=>
       int(5)
    }
    Encoded JSON: {"a":1,"b":2,"c":3,"d":4,"e":5}
    Array obtained after decoding: 
    object(stdClass)#1 (5) {
       ["a"]=>
       int(1)
       ["b"]=>
       int(2)
       ["c"]=>
       int(3)
       ["d"]=>
       int(4)
       ["e"]=>
       int(5)
    }
    
  • Filters

    It is important that the input data received in the form of client request is validated before processing in a PHP application. To perform input validation, the filter extension in PHP provides a number of filter functions, backed up by predefined filter constants and flags. The filter extension of PHP library also helps in sanitizing the input received by either GET or POST methods.

    The filter extension is a powerful feature that helps prevention of security vulnerabilities, such as SQL injection and cross-site scripting. The extension has two types of filters −

    Validation Filters

    Validation filters check if the data meets certain criteria. For example, you want to ensure that the user has correctly input an email field in the HTML form. The FILTER_VALIDATE_EMAIL will determine if the data is a valid email address. The validation filters, however, will not change the data itself.

    Sanitization Filters

    Sanitization refers to the process of removing undesired characters from the input. Hence, it may alter the data by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain, without performing validation.

    Filter Flags

    The filter extension in PHP defines a number of filter flags as follows −

    Sr.NoID & Description
    1FILTER_FLAG_STRIP_LOWStrips characters that have a numerical value <32.
    2FILTER_FLAG_STRIP_HIGHStrips characters that have a numerical value >127.
    3FILTER_FLAG_STRIP_BACKTICKStrips backtick characters.
    4FILTER_FLAG_ALLOW_FRACTIONAllows a period (.) as a fractional separator in numbers.
    5FILTER_FLAG_ALLOW_THOUSANDAllows a comma (,) as a thousands separator in numbers.
    6FILTER_FLAG_ALLOW_SCIENTIFICAllows an e or E for scientific notation in numbers.
    7FILTER_FLAG_NO_ENCODE_QUOTESIf this flag is present, single (‘) and double (“) quotes will not be encoded.
    8FILTER_FLAG_ENCODE_LOWEncodes all characters with a numerical value <32.
    9FILTER_FLAG_ENCODE_HIGHEncodes all characters with a numerical value >127.
    10FILTER_FLAG_ENCODE_AMPEncodes ampersands (&).
    11FILTER_NULL_ON_FAILUREReturns null for unrecognized values.
    12FILTER_FLAG_ALLOW_OCTALRegards inputs starting with a zero (0) as octal numbers.
    13FILTER_FLAG_ALLOW_HEXRegards inputs starting with 0x or 0X as hexadecimal numbers.
    14FILTER_FLAG_EMAIL_UNICODEAllows the local part of the email address to contain Unicode characters.
    15FILTER_FLAG_IPV4Allows the IP address to be in IPv4 format.
    16FILTER_FLAG_IPV6Allows the IP address to be in IPv6 format.
    17FILTER_FLAG_NO_PRIV_RANGEFails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
    18FILTER_FLAG_NO_RES_RANGEFails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4.Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10.
    19FILTER_FLAG_GLOBAL_RANGEFails validation for non global IPv4/IPv6 ranges
    20FILTER_FLAG_SCHEME_REQUIREDRequires the URL to contain a scheme part.
    21FILTER_FLAG_HOST_REQUIREDRequires the URL to contain a host part.
    22FILTER_FLAG_PATH_REQUIREDRequires the URL to contain a path part.
    23FILTER_FLAG_QUERY_REQUIREDRequires the URL to contain a query string.
    24FILTER_REQUIRE_SCALARRequires the value to be scalar.
    25FILTER_REQUIRE_ARRAYRequires the value to be an array.
    26FILTER_FORCE_ARRAYIf the value is a scalar, it is treated as array with the scalar value as only element.

    Filter Functions

    The filter extension includes the following filter functions −

    Sr.NoID & Description
    1filter_has_var()Checks if variable of specified type exists
    2filter_id()Returns the filter ID belonging to a named filter
    3filter_input_array()Gets external variables and optionally filters them
    4filter_input ()Gets a specific external variable by name and filters it
    5filter_list()Returns a list of all supported filters
    6filter_var_array()Gets multiple variables and optionally filters them
    7filter_var()Filters a variable with a specified filter

    Predefined Constants

    The above functions use one parameter called input_type which is one of the predefined enumerated constants representing how the input has been provided to the PHP script for filtering purpose.

    ConstantTypes
    INPUT_POST (int)POST Variables
    INPUT_GET (int)GET Variables
    INPUT_COOKIE (int)COOKIE Variables
    INPUT_ENV (int)ENV Variables
    INPUT_SERVER (int)SERVER Variables
    INPUT_SESSION (int)SESSION Variables
    INPUT_REQUEST (int)REQUEST Variables

    filter_has_var() function

    The filter_has_var() function checks if variable of specified type exists.

    filter_has_var(int$input_type,string$var_name):bool

    The input_type is one of predefined constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV; where as the var_name parameter is the name of a variable to check. The function returns true on success or false on failure.

    Example

    Visit the following PHP script on the XAMPP server.

    <?php
       if (!filter_has_var(INPUT_GET, "email")) {
    
      echo("Email not found");
    } else {
      echo("Email found");
    } ?>

    It will produce the following output −

    Visit http://localhost/[email protected]

    Email found
    

    filter_input() function

    The filter_input() function gets a specific external variable by name and filters it accorfing to the applied filter constant

    filter_input(int$type,string$var_name,int$filter=FILTER_DEFAULT,array|int$options=0):mixed

    The type parameter is one of the constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. Second parameter is var_name, the name of a variable to get. You can use the filter to be applied. Use any of the predefined filter flags. If omitted, FILTER_DEFAULT will be used

    The function returns the value of the requested variable on success, false if the filter fails, or null if the var_name variable is not set.

    Example

    Take a look at the following example −

    <?php
       if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
    
      echo("Email is not valid");
    } else {
      echo("Email is valid");
    } ?>

    It will produce the following output −

    If you use the URL http://localhost/[email protected],

    Email is valid
    

    If the URL is http://localhost/hello.php?email=a b [email protected],

    Email is not valid
    

    You can also use INPUT_POST type for validating the input received through the POST method −

    <?php
       if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL)) {
    
      echo("Email is not valid");
    } else {
      echo("Email is valid");
    } ?>

    To pass data with POST request, open the command prompt, and use the following CURL command

    curl -X POST -d "{\"email\": \"[email protected]\"}" http://localhost/hello.php
    

    filter_list() function

    The filter_list() function returns a list of all supported filters

    filter_list():array

    Example

    The function returns an array of names of all supported filters, empty array if there are no such filters.

    <?php
       print_r(filter_list());
    ?>

    It will produce the following output −

    Array
    (
       [0] => int
       [1] => boolean
       [2] => float
       [3] => validate_regexp
       [4] => validate_domain
       [5] => validate_url
       [6] => validate_email
       [7] => validate_ip
       [8] => validate_mac
       [9] => string
       [10] => stripped
       [11] => encoded
       [12] => special_chars
       [13] => full_special_chars
       [14] => unsafe_raw
       [15] => email
       [16] => url
       [17] => number_int
       [18] => number_float
       [19] => add_slashes
       [20] => callback
    )
    

    filter_input_array() function

    The filter_input_array() gets external variables and optionally filters them.

    filter_input_array(int$type,array|int$options=FILTER_DEFAULT,bool$add_empty=true):array|false|null

    This function is useful for retrieving many values without repetitively calling filter_input().

    The type parameter is one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

    The options parameter is an array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

    The function returns an array containing the values of the requested variables on success. If the input array designated by type is not populated, the function returns null if the FILTER_NULL_ON_FAILURE flag is not given, or false otherwise. For other failures, false is returned.

    Example

    To include an array in the HTTP request, we use the following HTML form in “hello.html”, and send it by POST method.

    <!DOCTYPE html><html><body><h1>Filter Input Array</h1><form action="hello.php" method="POST"><p><label for="email">Enter your email:</label><input type="text" id="email" name="email"></p><p><label for="age">Enter your age<label><input type = "text" id="age" name="age"></p><input type="submit"></form></body></html>

    The PHP script to validate the input array is as follows −

    <?php
       $filters = array (
    
      "age" =&gt; array ("filter"=&gt;FILTER_VALIDATE_INT, 	
         "options"=&gt;array("min_range"=&gt;20,"max_range"=&gt;40) ),
      "email" =&gt; FILTER_VALIDATE_EMAIL
    ); print_r(filter_input_array(INPUT_POST, $filters)); ?>

    Open the HTML form and enter 30 as age, [email protected] as email, the result will be an array, validating both the inputs −

    Array ( [age] => 30 [email] => [email protected] )
    

    Try giving invalid inputs such as “age=15”. The output array will show a null value for age key

    Array ( [age] => [email] => [email protected] )

  • Design Patterns

    In the theory of software engineering, the term “Design patterns” generally refers to a reusable solution that can be used as a template for developing applications to address commonly occurring problems. You can consider the software design patterns as formalized best practices when developing software solutions.

    Most of the standard design patterns can be very effectively implemented in developing applications in PHP. In this chapter, we shall learn how to apply some of the popular design patterns in developing PHP applications.

    Singleton Pattern

    The singleton design pattern is useful when you want to restrict the instantiation of an object of a certain class to only one instance. The name “singleton pattern” comes from the concept of singleton in Mathematics. Singleton pattern ensures that there will be only one instance, having a global access to it throughout the application.

    Typical application of singleton pattern is creation of a database connection object, which must be created once in the lifetime of an application.

    Example

    In the following code, the DataBaseConnector class can be instantiated only once, otherwise a message that disallows duplicate object will be issued.

    <?php
       class DataBaseConnector {				
    
      private static $obj;				
      private final function __construct() {
         echo __CLASS__ . " object created for first time ". PHP_EOL;
      }
      public static function getConnect() {
         if (!isset(self::$obj)) {
            self::$obj = new DataBaseConnector();
            return self::$obj;
         } else {
            echo "connection object could not be created again" . PHP_EOL;
         }
      }
    } $obj1 = DataBaseConnector::getConnect(); $obj2 = DataBaseConnector::getConnect(); var_dump($obj1 == $obj2); ?>

    It will produce the following output −

    DataBaseConnector object created for first time 
    connection object could not be created again
    bool(false)
    

    Factory Pattern

    This is one of the most commonly used design patterns. In this pattern, you dont declare the object of the desired class directly, but another class is provided whose static method creates the required object.

    Example

    The following example demonstrates how factory design pattern works −

    <?php
       class Automobile {
    
      private $bikeMake;
      private $bikeModel;
      public function __construct($make, $model) {
         $this-&gt;bikeMake = $make;
         $this-&gt;bikeModel = $model;
      }
      public function getMakeAndModel() {
         return $this-&gt;bikeMake . ' ' . $this-&gt;bikeModel;
      }
    } class AutomobileFactory {
      public static function create($make, $model) {
         return new Automobile($make, $model);
      }
    } $pulsar = AutomobileFactory::create('ktm', 'Pulsar'); print_r($pulsar->getMakeAndModel()); ?>

    It will produce the following output −

    ktm Pulsar
    

    Strategy Pattern

    The strategy pattern recommends an approach where you encapsulate specific families of algorithms allowing the client class responsible for instantiating a particular algorithm. The class that implements the pattern has no knowledge of the actual implementation.

    Example

    Here is a code that demonstrates the use of strategy pattern. We have an interface whose case() method is implemented differently by two different classes. The object of testdata class calls the respective case() methods indirectly through its own process() method.

    <?php
       interface example {
    
      public function case($str);
    } class ucase implements example {
      public function case($str) {
         return strtoupper($str);
      } 
    } class lcase implements example {
      public function case($str) {
         return strtolower($str);
      }
    } class testdata {
      private $data;
      public function __construct($input) {
         $this-&gt;data = $input;
      }
      public function process(example $type) {
         return $this-&gt;data = $type-&gt;case($this-&gt;data);
      }
    } $str = "hello"; $obj = new testdata($str); echo $obj->process(new ucase) . PHP_EOL; $str = "HELLO"; echo $obj->process(new lcase); ?>

    It will produce the following output −

    HELLO
    Hello
    

    MVC Design Pattern

    MVC, which stands for Model, View and Controller, is a very popular softeware architecture pattern. Most of the PHP networks such as Laravel, Symfony etc. implement the MVC architecture.

    The separation of the role of each layer in an application is as follows −

    • Model − Refers to the data structure. In this case, the database.
    • View − Refers to the user interface. The HTML and CSS.
    • Controller − The “middleman” doing the processing. Accepts input from the view, and works with the model. Self-explanatory, the PHP scripts and libraries themselves.

    The View acts as the GUI, the Model acts as the back-end and the Control acts as an adapter. Here, three parts are interconnected with each other. It will pass the data and access the data between each other.

    Example

    Let us implement the MVC design pattern in pure PHP, JavaScript and HTML in the example below −

    The presentation layer of the application is view.php, which renders a HTML form. The user submits the data to a controller script. The result returned by the controller is rendered on the web page with a bit of JavaScript

    view.php

    <!DOCTYPE html><html><head><title>View (User Interface)</title><link rel="stylesheet" href="style.css"></head><body><form id="mysearch" action="controller.php" method="POST"><input type="text" id = "nm" name="search" required><input type="submit" value="Search"></form><div id="results"></div><script>
    
      let results = document.getElementById("results");
      results.innerHTML = "";
    </script><?php
      session_start();
      if (isset($_SESSION['result'])) {
         $arr=$_SESSION['result'];
         foreach ($arr as $obj) {<strong>?&gt;</strong>&lt;script&gt;
               results.innerHTML += "&lt;div&gt;<strong>&lt;?php</strong> echo $obj['id'] . "-" . 
    		      $obj['name'] . "&lt;/div&gt;"; <strong>?&gt;</strong>";
            &lt;/script&gt;<strong>&lt;?php</strong>
         }
      }
    ?></body></html>

    The controller script requires model.php, and uses the database object, calls the select method to fetch data from the database. The result is stored in the current session so that it can be accessed on the view page.

    controller.php

    <?php
       session_start();
       require "model.php";
       $results = $_DB->select(
    
      "SELECT * FROM users WHERE name LIKE ?",
      ["%{$_POST["search"]}%"]
    ); $_SESSION['search'] = $_POST['search']; $_SESSION['result'] = $results; Header("Location: view.php", true); ?>

    The model layer of the application is coded in “model.php”. It establishes connection with mysql database named mydb, using PDO extension.

    model.php

    <?php
       class DB {
    
      public $error = "";
      private $pdo = null;
      private $stmt = null;
      var $dsn="localhost";  
      var $dbName="myDB";  
      var $username="root";       
      var $password=""; 
      function __construct () {
         $this-&gt;pdo = new PDO("mysql:host=$this-&gt;dsn;dbname=$this-&gt;
    	    dbName",$this-&gt;username,$this-&gt;password); 
      }
      function __destruct () {
         if ($this-&gt;stmt!==null) { $this-&gt;stmt = null; }
         if ($this-&gt;pdo!==null) { $this-&gt;pdo = null; }
      }
      function select ($sql, $data=null) {
         $this-&gt;stmt = $this-&gt;pdo-&gt;prepare($sql);
         $this-&gt;stmt-&gt;execute($data); 
         return $this-&gt;stmt-&gt;fetchAll();
      }
    } $_DB = new DB(); ?>

    The backend mydb database must have a users table with ID and NAME fields.

    -- Table structure for table users--CREATETABLEusers(idbigint(20)NOTNULL,namevarchar(255)NOTNULL)ENGINE=InnoDB DEFAULTCHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;---- Dumping data for table users--INSERTINTOusers(id,name)VALUES(21,'Ahmad Shaikh'),(24,'Akshay Wadkar'),(26,'Bridget Wooten'),(10,'Coby Kelleigh'),(20,'Dashan Shah'),(12,'Elizabeth Taylor'),(41,'Issac Newton'),(34,'Julia Roberts'),(31,'Junior Mahmood'),(32,'Kailas Bende'),(47,'Karan Sharma'),(16,'Kenneth Sanders'),(28,'Kirstie Thomas'),(33,'Lawrence Murphy'),(14,'Leah Shan'),(51,'Marcus Best'),(29,'Maya Pande'),(50,'Nathaniel Khan'),(6,'Richard Breann'),(54,'Rowan Avalos'),(3,'Rusty Terry'),(37,'Sacha Gross'),(27,'Sally Castillo'),(11,'Sarah Sanders'),(18,'Seth Sonnel'),(38,'Shannon Peterson'),(25,'Shayan Clements'),(49,'Shoaib Vickers'),(43,'Simran Kaur'),(35,'Sulaiman Gilmour'),(44,'Taran Morin'),(48,'Taran Morin'),(22,'Thelma Kim'),(8,'Tillie Sharalyn'),(36,'Virgil Collier');

    Start the application by visiting “http://localhost/view.php” in the browser. Enter a search term corresponding to the names having required letters.

    PHP Design Patterns
  • PHP vs Frameworks

    PHP is by far the most popular server-side programming language for web application development, with nearly 75% of websites using PHP either in its core form or one of the PHP frameworks available. To make a choice between using “core PHP” or frameworks for web development, we need to understand the pros and cons of both.

    To give a simple analogy, developing a web application purely with core PHP is like solving a mathematical problem manually by writing down each step on the paper. On the other hand, using a framework is similar to using tools such as a calculator to solve a problem. Just as a calculator, the frameworks are useful tools for rapid application development.

    Core PHP vs Frameworks Pros and Cons

    A web framework, especially a PHP framework is a collection of one or more PHP libraries and classes. It provides a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code scratch. It provides a reusable software environment that quickly builds a minimal working template application.

    Developing a web application purely in core PHP has its own advantages and disadvantages −

    • It gives the developer better control and flexibility.
    • At the same time, for a larger application developed with core PHP only can become unwieldy, difficult to manage and maintain.

    Now, let’s turn to pros and cons of using PHP Frameworks −

    • A PHP framework such as Symfony, Laravel or Yii offers a more standardized approach towards web application development. With most of the routine and repetitive part handled by the framework, the developer can concentrate more on the application logic. Hence, there is lesser time wasted in debugging.
    • On the other hand, a framework is not as flexible compared to core PHP. The skeleton template of the application is readily made available by the framework, leaving the developer to customize the functionality only within the scope defined by the framework.

    The MVC Architecture

    Most of the web application frameworks employ the MVC (Model, View and Controller) architecture, which makes it a lot easier to write quality, robust code, by separating the logic from the style.

    PHP Core PHP Vs Frameworks

    If you wish to use the core PHP features for your application development, you are free to adopt an object oriented approach or a modular approach, whichever suits you.

    Built-in Security Measures

    PHP frameworks offer built-in security measures to be incorporated in a web applications.

    • If you choose to develop an application with core PHP, you will have to provide the security measures explicitly.
    • Most of the frameworks however have a few external dependencies, which may leave the application rather vulnerable, as compared to a core PHP application which is a self-contained solution.

    A framework-based application may be a little slow when it comes to performance, as compared to core PHP application, especially for a smaller application.

    Comparison: Core PHP vs Frameworks

    The comparison between the two can be summarized as follows −

    • For smaller applications, core PHP is preferrable over framework.
    • Framework offers rapid development and code reusability.
    • Frameworks are less flexible.
    • Using core PHP features, the developer has complete control.
    • For large applications, the MVC architecture is helpful.
    • Frameworks offer integrated authorization and authentication support. In a core PHP application, the security rules need to be explicitly defined.
  • Frameworks

    The PHP ecosystem has a number of web frameworks. Some of the popular PHP web frameworks are Laravel, Yii, CakePHP etc. While one can build a web application with the help of core PHP, developers are increasingly preferring web frameworks for rapid application development.

    What are Software Frameworks?

    In computer programming, a software framework is a collection of libraries and classes that provide a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code for routine but tedious low-level processes.

    A framework provides a reusable software environment that quickly builds a minimal working template application. Developer can then modify these blocks for additional functionality.

    Each framework is built to help the developer build an application of a certain type. For example, web frameworks (sometimes also called “web application framework”) are used for the development of web applications including web services, web resources, and web APIs.

    In this chapter, let us take a brief overview of some of the popular PHP frmeworks.

    FuelPHP

    FuelPHP (https://fuelphp.com/) works based on Model View Control and having innovative plug ins. FuelPHP supports router-based theory where you might route directly to a nearer the input uri, making the closure the controller and giving it control of further execution.

    PHP Frameworks 1

    CakePHP

    CakePHP (https://cakephp.org/) is a great source to build up simple and great web application in an easy way. Some great features which are inbuilt in PHP are input validation, SQL injection prevention that keeps you application safe and secure.

    PHP Frameworks 2

    FlightPHP

    FlightPHP (https://flightphp.com/) is very helpful to make RESTful web services and it is under MIT licence.

    PHP Frameworks 3

    Symfony

    Symfony is for highly professional developers to build websites with PHP components such as Drupal, PHPBB, laravel, eX, OROCRM and piwik.

    PHP Frameworks 4

    yiiFramework

    YiiFramework (https://www.yiiframework.com/) works based on web 2.0 with high end security. It included input Validation, output filtering, and SQL injection.

    PHP Frameworks 5

    Laravel

    Laravel (https://laravel.com/) is most useful for RESRful Routing and light weight bled tempting engine. Laravel has integrated with some of great components of well tested and reliable code.

    PHP Frameworks 6

    Zend

    Zend (https://framework.zend.com/) is Modern frame work for performing high end web applications. This works based on Cryptographic and secure coding tools. Zend Framework is a collection of professional PHP packages with more than 570 million installations.

    It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features.

    PHP Frameworks 7

    Codeigniter

    Codeigiter is simple to develop small footprint for developer who need simple and elegant tool kit to create innovative web applications.

    PHP Frameworks 8

    Phalcon PHP

    Pholcon (https://phalcon.io/en-us) is a PHP framework that works based on MVC and integrated with innovative architecture to do perform faster.

    PHP Frameworks 9

    PHPixie

    PHPixie (https://phpixie.com/) works based on MVC and designed for fast and reliability to develop web sites.

    PHP Frameworks 10

    Agavi

    Agavi is a powerful and scalable PHP5 application framework and it follows the MVC model. Agavi can help PHP developers in writing clean and maintainable code.

  • For PERL Developers

    PERL is a dynamically typed, high level and general-purpose programming language. It is normally believed that PERL is an acronym for Practical Extraction and Reporting Language. PHP on the other hand is also a general-purpose scripting language. Initially PHP used to be a short for Personal Home Page, but these days it has now been recognized as a recursive acronym PHP: Hypertext Preprocessor.

    In this chapter, certain major similarities and differences in between PHP and PERL are listed. This will help PERL developers to understand PHP very quickly and avoid common mistakes.

    Similarities between PERL and PHP

    Both Perl and PHP are scripting languages. They are not used to build native standalone executables in advance of execution.

    Early versions of PHP were inspired by PERL. PHP’s basic syntax is very similar to PERL. Both share a lot of syntactic features with C. Their code is insensitive to whitespace, Each statement is terminated by semicolons.

    Both PHP and PERL use curly braces to organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas, in both the cases.

    • All variables in PHP look like scalar variables in PERL: a name with a dollar sign ($) in front of it.
    • Since both the languages are dynamically typed, you dont need to declare the type of a PHP as well as a PERL variable before using it.
    • In PHP, as in PERL, variables have no intrinsic type other than the value they currently hold. You can store either number or string in same type of variable.
    • Both PHP and Perl do more interpretation of double-quoted strings (“string”) than of single-quoted strings (‘string’).

    Differences between PERL and PHP

    PHP can be embedded inside HTML. Although it is possible to run a PHP script from the command line, it is more popularly used as a server-side scripting language on a Web server and used for producing Web pages.

    If you are used to writing CGI scripts in PERL, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block.

    No @ or % variables − PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound. In PERL, the array variable is prefixed with @ symbol. Also, the hash variable is prefixed by % symbol.

    Unlike PERL, PHP has a single datatype called an array which can be an indexed array or associative array, which is similar to hash in PERL.

    Function calls in PHP look pretty much like subroutine calls in PERL. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the case in PERL.

    Scope of variables in PERL is global by default. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default.

    No module system in PHP as such. In PHP there is no real distinction between normal code files and code files used as imported libraries.

    Break and continue rather than next and last PHP is more like C language and uses break and continue instead of next and last statement as in PERL.

    No elsif − A minor spelling difference: Perl’s elsif is PHP’s elseif.

    In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */) and Java-style single-line comments (// comment).

    Regular expressions − PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its “Perl-compatible” regular expression functions.

  • For C Developers

    If you have a prior knowledge of C programming, learning PHP becomes a lot easier, especially the basics. Although PHP is a lot like C, it is bundled with a whole lot of Web-specific libraries, with everything hooked up directly to your favorite Web server.

    The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. PHP script can also be executed from the command line, much like a C program.

    The syntax of statements and function definitions should be familiar, except that variables are always preceded by $, and functions do not require separate prototypes.

    Let us take a look at some of the similarities and differences in PHP and C −

    Similarities Between C and PHP

    Syntax − Broadly speaking, PHP syntax is the same as in C, which is what makes learning PHP easier, if you are already conversant with C.

    Similar to C, PHP Code is blank insensitive, statements are terminated with semicolons.

    function calls have the same structure

    my_function(expression1, expression2){
       Statements;}

    Curly brackets are used to put multiple statements into blocks.

    PHP supports C and C++-style comments (/* */ as well as //), and also Perl and shell-script style (#).

    Operators − The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C.

    Control Structures − The basic control structures (if, switch, while, for) behave as they do in C, including supporting break and continue. One notable difference is that switch in PHP can accept strings as case identifiers.

    PHP also has foreach looping construct that traverses the collections such as arrays.

    Function Names − As you peruse the documentation, you.ll see many function names that seem identical to C functions.

    Differences Between C and PHP

    Dollar Sign − All variable names are prefixed with a leading $. Variables do not need to be declared in advance of assignment, and they have no intrinsic type. PHP is a dynamically typed language, as against C being a statically typed language.

    Types − PHP has only two numerical types: integer (corresponding to a long in C) and double (corresponding to a double in C). In PHP, float is synonymous to double. Strings are of arbitrary length. There is no separate char type in PHP, as is the case in C.

    Type Conversion − C is a strongly typed language, as type of a variable must be declared before using, and the types are checked at compile time. PHP on the other hand, is a weakly typed language, types are not checked at compile time, and type errors do not typically occur at runtime either. Instead, variables and values are automatically converted across types as needed.

    Arrays − Arrays have a syntax superficially similar to C’s array syntax, but they are implemented completely differently. In C, an array is a collection of similar data types. In a PHP array, the items may be of different types. PHP arrays are actually associative arrays or hashes, and the index can be either a number or a string. They do not need to be declared or allocated in advance.

    No Struct Type − The struct keyword in C is used to define a new data type. There is no struct keyword or its equivalent in PHP, partly because the array and object types together make it unnecessary. The elements of a PHP array need not be of a consistent type.

    No Pointers − Pointers are an important concept in C. There are no pointers available in PHP, although the tapeless variables play a similar role. Unlike C, PHP does support variable references. You can also emulate function pointers to some extent, in that function names can be stored in variables and called by using the variable rather than a literal name.

    No Prototypes − Functions do not need to be declared before their implementation is defined, as long as the definition can be found somewhere in the current code file or included files. On the contrary, a C function must defined before it is used.

    No main() − In a C program, the main() function is the entry point, irrespective of where it is present in the code. A PHP program on the other hand starts execution from the first statement in the script

    Memory Management − The PHP engine is effectively a garbage-collected environment (reference-counted), and in small scripts there is no need to do any deallocation. You should freely allocate new structures – such as new strings and object instances. IN PHP5, it is possible to define destructor for objects, but there is are no free or delete keywords as in C/C++. Destructor are called when the last reference to an object goes away, before the memory is reclaimed.

    Compilation and Linking − PHP is an interpreted language. Hence, the compiled version of PHP script is not created. A C program is first compiled to obtain the object code, which is then linked to the required libraries to build an executable. There is no separate compilation step for PHP scripts. A PHP script cannot be turned into a self executable.

    Permissiveness − As a general matter, PHP is more forgiving than C (especially in its type system) and so will let you get away with new kinds of mistakes. Unexpected results are more common than errors.

  • Bugs Debugging

    A bug in a PHP code refers to an error in the program that leads to unexpected results or crash. A systematic approach towards the process of finding bugs before users do is called debugging. In this chapter, some important tips to trace bugs in a PHP code are given.

    Programs rarely work correctly the first time. Many things can go wrong in your program that can cause the PHP interpreter to generate an error message. You have a choice about where those error messages go. The messages can be sent along with other program output to the web browser. They can also be included in the “web server error log”.

    To make error messages display in the browser, set the “display_errors” configuration directive to ON. Ensure that the following settings are enabled in the “php.ini” file.

    display_errors=On
    display_startup_errors=On
    

    You can also use the ini_set() function to override the “pnp.ini” configuration −

    ini_set('display_errors',1)ini_set('display_startup_errors',1)

    To send errors to the web server error log, set “log_errors” to ON. You can set them both to On if you want error messages in both places.

    PHP defines some constants that you can use to set the value of error_reporting such that only errors of certain types get reported −

    • E_ALL (for all errors except strict notices)
    • E_PARSE (parse errors)
    • E_ERROR (fatal errors)
    • E_WARNING (warnings)
    • E_NOTICE (notices)
    • E_STRICT (strict notices)

    While writing your PHP program, it is a good idea to use PHP-aware editors like BBEdit or Emacs. One of the special features of these editors is syntax highlighting. It changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black.

    VS Code from Microsoft is also a good choice for editing PHP code. If you install VS Code extension Intelephense, you will get type hints and error message as you enter PHP statements in the editor window.

    Another feature is quote and bracket matching, which helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as “}”, the editor highlights the opening “{” that it matches.

    Points to Check while Debugging a Code

    One needs to verfity the following points while debugging a program code −

    Missing Semicolons

    Every PHP statement ends with a semicolon (;). PHP doesn’t stop reading a statement until it reaches a semicolon. If you leave out the semicolon at the end of a line, PHP continues reading the statement on the following line.

    Not Enough Equal Signs

    When you ask whether two values are equal in a comparison statement, you need two equal signs (==). Using one equal sign is a common mistake.

    Misspelled Variable Names

    If you misspelled a variable then PHP understands it as a new variable. Remember: To PHP, $test is not the same variable as $Test.

    Missing Dollar Signs

    A missing dollar sign in a variable name is really hard to see, but at least it usually results in an error message so that you know where to look for the problem.

    Troubling Quotes

    You can have too many, too few, or the wrong kind of quotes. So check for a balanced number of quotes.

    Missing Parentheses and curly brackets

    They should always be in pairs.

    Array Index

    An array in PHP is a collection of items, each item assigned an incrementing index starting with 0.

    Moreover, handle all the errors properly and direct all trace messages into system log file so that if any problem happens then it will be logged into system log file and you will be able to debug that problem.