Category: PHP

  • Encryption

    Early versions of PHP included mcrypt extension, that provided encryption/decryption capabilities. Due to lack of maintenance, the mycrypt extension has been deprecated and removed from PHP 7.2 version onwards. PHP now includes OpenSSL library that has an extensive functionality to support encryption and decryption features.

    OpenSSL supports various encryption algorithms such as AES (Advanced Encryption Standard). All the supported algorithms can be obtained by invoking openssl_get_cipher_methods() function.

    The two important functions in OpenSSL extension are −

    • openssl_encrypt() − Encrypts data
    • openssl_decrypt() − Decrypts data

    The openssl_encrypt() Function

    This function encrypts the given data with given method and key, and returns a raw or base64 encoded string −

    openssl_encrypt(string$data,string$cipher_algo,string$passphrase,int$options=0,string$iv="",string&$tag=null,string$aad="",int$tag_length=16):string|false

    The function has the following parameters −

    Sr.NoParameter & Description
    1dataThe plaintext message data to be encrypted.
    2cipher_algoThe cipher method.
    3passphraseThe passphrase. If the passphrase is shorter than expected, padded with NULL characters; if the passphrase is longer than expected, it is truncated.
    4optionsoptions is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
    5ivA non-NULL Initialization Vector.
    6tagThe authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).
    7aadAdditional authenticated data.
    8tag_lengthThe length of the authentication tag. Its value can be between 4 and 16 for GCM mode.

    The function returns the encrypted string on success or false on failure.

    The openssl_decrypt() Function

    This function takes a raw or base64 encoded string and decrypts it using a given method and key.

    openssl_decrypt(string$data,string$cipher_algo,string$passphrase,int$options=0,string$iv="",?string$tag=null,string$aad=""):string|false

    The openssl_decrypt() function uses the same parameters as the openssl_encrypt function.

    This function returns the decrypted string on success or false on failure.

    Example

    Take a look at the following example −

    <?php
       function sslencrypt($source, $algo, $key, $opt, $iv) {
    
      $encstring = openssl_encrypt($source, $algo, $key, $opt, $iv);
      return $encstring;
    } function ssldecrypt($encstring, $algo, $key, $opt, $iv) {
      $decrstring = openssl_decrypt($encstring, $algo, $key, $opt, $iv);
      return $decrstring;
    } // string to be encrypted $source = "PHP: Hypertext Preprocessor"; // Display the original string echo "Before encryption: " . $source . "\n"; $algo = "BF-CBC"; $opt=0; $ivlength = openssl_cipher_iv_length($algo); $iv = random_bytes($ivlength); $key = "abcABC123!@#"; // Encryption process $encstring = sslencrypt($source, $algo, $key, $opt, $iv); // Display the encrypted string echo "Encrypted String: " . $encstring . "\n"; // Decryption process $decrstring = ssldecrypt($encstring, $algo, $key, $opt, $iv); // Display the decrypted string echo "Decrypted String: " . $decrstring; ?>

    It will produce the following output −

    Before encryption: PHP: Hypertext Preprocessor
    Encrypted String: 
    Decrypted String:

  • Hashing

    The term “hashing” represents a technique of encrypting data (specially a text) to obtain a fixed-length value. PHP library includes a number of functions that can perform hashing on data by applying different hashing algorithms such as md5, SHA2, HMAC etc. The encrypted value obtained is called as the hash of the original key.

    Processing of hashing is a one-way process, in the sense, it is not possible to reverse the hash so as to obtain the original key.

    Applications of Hashing

    The hashing technique is effectively used for the following purposes −

    Password Authentication

    We often register for various online applications such as gmail, Facebook etc. You are required to fill up a form wherein you create a password for an online account. The server hashes your password and the hashed value is stored in the database. At the time of logging in, the password submitted is hashed and compared with the one in the database. This protects your password from being stolen.

    Data Integrity

    One of the important uses of hashing is to verify if the data has not been tampered with. When a file is downloaded from the internet, you are shown its hash value, which you can compare with the downloaded to make sure that the file has not been corrupted.

    The Process of Hashing

    The process of hashing can be represented by the following figure −

    PHP Hashing

    Hashing Algorithms in PHP

    PHP supports a number of hashing algorithms −

    • MD5 − MD5 is a 128-bit hash function that is widely used in software to verify the integrity of transferred files. The 128-bit hash value is typically represented as a 32-digit hexadecimal number. For example, the word “frog” always generates the hash “8b1a9953c4611296a827abf8c47804d7”
    • SHA − SHA stands for Secure Hash Algorithm. It’s a family of standards developed by the National Institute of Standards and Technology (NIST). SHA is a modified version of MD5 and is used for hashing data and certificates. SHA-1 and SHA-2 are two different versions of that algorithm. SHA-1 is a 160-bit hash. SHA-2 is actually a family of hashes and comes in a variety of lengths, the most popular being 256-bit.
    • HMAC − HMAC (Hash-Based Message Authentication Code) is a cryptographic authentication technique that uses a hash function and a secret key.
    • HKDF − HKDF is a simple Key Derivation Function (KDF) based on the HMAC message authentication code.
    • PBKDF2 − PBKDF2 (Password-Based Key Derivation Function 2) is a hashing algorithm that creates cryptographic keys from passwords.

    Hash Functions in PHP

    The PHP library includes several hash functions −

    The hash_algos Function

    This function returns a numerically indexed array containing the list of supported hashing algorithms.

    hash_algos():array

    The hash_file Function

    The function returns a string containing the calculated message digest as lowercase hexits.

    hash_file(string$algo,string$filename,bool$binary=false,array$options=[]):string|false

    The algo parameter is the type of selected hashing algorithm (i.e. “md5”, “sha256”, “haval160,4”, etc.). The filename is the URL describing location of file to be hashed; supports fopen wrappers.

    Example

    Take a look at the following example −

    <?php
       /* Create a file to calculate hash of */
       $fp=fopen("Hello.txt", "w");
       $bytes = fputs($fp, "The quick brown fox jumped over the lazy dog.");
       fclose($fp);
       echo hash_file('md5', "Hello.txt");
    ?>

    It will produce the following output −

    5c6ffbdd40d9556b73a21e63c3e0e904
    

    The hash() Function

    The hash() function generates a hash value (message digest) −

    hash(string$algo,string$data,bool$binary=false,array$options=[]):string

    The algo parameter is the type of selected hashing algorithm (i.e. “md5”, “sha256”, “haval160,4”, etc..). The data parameter is the message to be hashed. If the binary parameter is “true“, it outputs raw binary data; “false” outputs lowercase hexits.

    Example

    The function returns a string containing the calculated message digest as lowercase hexits.

    <?php
       echo "Using SHA256 algorithm:" . hash('sha256', 'The quick brown fox jumped over the lazy dog.'). PHP_EOL;
       echo "Using MD5 algorithm:",hash('md5', 'The quick brown fox jumped over the lazy dog.'), PHP_EOL;
       echo "Using SHA1 algorithm:" . hash('sha1', 'The quick brown fox jumped over the lazy dog.');
    ?>

    It will produce the following output −

    Using SHA256 algorithm:68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483
    Using MD5 algorithm:5c6ffbdd40d9556b73a21e63c3e0e904
    Using SHA1 algorithm:c0854fb9fb03c41cce3802cb0d220529e6eef94e

  • 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.