Author: admin

  • PHP Closure::call()

    In PHP, a closure is an anonymous function that has access to the variables in the scope in which it was created, even after that scope has closed. You need to specify use keyword in it.

    Closures are objects that encapsulate the function code and the scope in which they were created. With PHP 7, a new closure::call() method was introduced to bind an object scope to a closure and invoke it.

    Methods in the Closure Class

    The Closure class has the following methods including the call() method −

    finalclassClosure{/* Methods */private__construct()publicstaticbind(Closure$closure,?object$newThis,object|string|null$newScope="static"):?ClosurepublicbindTo(?object$newThis,object|string|null$newScope="static"):?Closurepubliccall(object$newThis,mixed...$args):mixedpublicstaticfromCallable(callable$callback):Closure}

    The call() method is a static method of Closure class. It has been introduced as a shortcut the bind() or bindTo() methods.

    The bind() method Duplicates a closure with a specific bound object and class scope while the bindTo() method duplicates the closure with a new bound object and class scope.

    The call() method has the following signature −

    publicClosure::call(object$newThis,mixed...$args):mixed

    The call() method temporarily binds the closure to newThis, and calls it with any given parameters.

    With version prior to PHP 7, the bindTo() method can be used as follows −

    <?php
       class A {
          private $x = 1;
       }
    
       // Define a closure Pre PHP 7 code
       $getValue = function() {
          return $this->x;
       };
    
       // Bind a clousure
       $value = $getValue->bindTo(new A, 'A'); 
       print($value());
    ?>

    The program binds the $getValue which is a closure object, to the object of A class and prints the value of its private variable $x it is 1.

    With PHP 7, the binding is achieved by call() method as shown below −

    <?php
       class A {
          private $x = 1;
       }
    
       // PHP 7+ code, Define
       $value = function() {
          return $this->x;
       };
    
       print($value->call(new A));
    ?>
  • PHP Swapping Variables

    PHP doesnt provide any built-in function with which you can swap or interchange values of two variables. However, there are a few techniques which you can use to perform the swap.

    One of the most straightforward approaches is to use a third variable as a temporary place holder to facilitate swapping. Using the arithmetic operators in a specific order also is very effective. You can also use the binary XOR operator for swapping purpose. In this chapter, we shall implement these swapping techniques in PHP

    Temporary Variable

    This is logically the most obvious and the simplest approach. To swap values of “a” and “b”, use a third variable “c”. Assign the value of “a” to “c”, overwrite “a” with existing value of “b” and then set “b” to the earlier value of “a” that was stored in “c”.

    Example

    Take a look at the following example −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $c = $a; 
       $a = $b;
       $b = $c;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
    

    Using addition (+) Operator

    This solution takes the advantage of the fact that subtracting a number from the sum of two numbers gives back the second number. In other words, “sum(a+b) a” is equal to “b” and vice versa.

    Example

    Let us take advantage of this property to swap “a” and “b” −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $a = $a + $b;
       $b = $a - $b;
       $a = $a - $b;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
    

    You can also use the other arithmetic operators subtraction (-), multiplication (*) and division (/) in a similar manner to perform swapping.

    Using list() Function

    The list() function in PHP unpacks the array in separate variables. This helps in our objective of performing swap between two variables. To do that, build an array of “a” and “b”, and then unpack it to “b” and “a” variables to obtain “a” and “b” with interchanged values.

    Example

    Take a look at the following example −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $arr = [$a, $b];
       list($b, $a) = $arr;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
    

    Bitwise XOR

    The bitwise XOR (^) operator can also be used to swap the value of two variables “x” and “y”. It returns 1 when one of two bits at same position in both operands is 1, otherwise returns 0.

    Example

    Take a look at the following example −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $a = $a ^ $b;
       $b = $a ^ $b;
       $a = $a ^ $b;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
  • PHP HTTP Authentication

    In PHP, the header() function is used to send an “Authentication Required” message to the client browser causing it to pop up a Username/Password input window. In fact header() allows you to send any raw HTTP header.

    header(string$header,bool$replace=true,int$response_code=0):void

    The string parameter is passed to the header() function. For example

    header("HTTP/1.1 404 Not Found");

    It is used to figure out the HTTP status code to send.

    You can also use header() function to redirect the browser to another URL.

    Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array. Only “Basic” and “Digest” authentication methods are supported.

    <?php
    
       /* Redirect browser */
       header("Location: http://www.example.com/"); 
    
       /* Make sure that code below does not get executed when we redirect. */
       exit;
       
    ?>

    The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type, and response_code parameter forces the HTTP response code to the specified value.

    To be able to force he client authentication, you need a .htaccess file in document root folder. Open a new text file, put the following text in it, and save it with .htaccess as its name.

    CGIPassAuth On
    

    Example

    An example script fragment which would force client authentication on a page is as follows −

    <?php
       if (!isset($_SERVER['PHP_AUTH_USER'])) {
          header('WWW-Authenticate: Basic realm="My Realm"');
          header('HTTP/1.0 401 Unauthorized');
          echo 'User hits Cancel button';7
          exit;
       } else {
          echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
          echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
       }
    ?>

    Output

    When you visit the script in a browser, it pops up a dialog box as shown −

    PHP HTTP Authentication 1

    Once you click on the sign in button, there may be a backend script to authenticate the login credentials. Once authenticated, two server variables will be created with the keys PHP_AUTH_USER and PHP_AUTH_PW, which can be verified with the output of phpinfo() function.

    PHP HTTP Authentication 2
  • PHP System Calls

    PHP’s library of built-in function includes a category of functions that deal with invoking operating system utilities and external programs from within the PHP code. In this chapter, we shall discuss the PHP functions used to perform system calls.

    The system() Function

    The system() function is similar to the system() function in C that it executes the given command and outputs the result.

    system(string$command,int&$result_code=null):string|false

    The system() call tries to automatically flush the web server’s output buffer after each line of output if PHP is running as a server module. It returns the last line of the command output on success, and false on failure.

    Example

    The following PHP snippet invokes DIR command of Windows OS and displays the list of files in the current directory.

    <?php
       echo '<pre>';
    
       // Outputs all the result of DOS command "dir", and returns
       // the last output line into $last_line. Stores the return value
       // of the shell command in $retval.
       $last_line = system('dir/w', $retval);
    
       // Printing additional info
       echo '
       </pre>
       <hr />Last line of the output: ' . $last_line . '
       <hr />Return value: ' . $retval;
    ?>

    It will produce the following output −

    Volume in drive C has no label.
    Volume Serial Number is 7EE4-E492
    
    Directory of C:\xampp\htdocs
    [.]                 [..]                applications.html   bitnami.css
    [dashboard]         employee.csv        favicon.ico         hello.csv
    hello.html          hello.php           homepage.php        [img]
    index.php           [Langi]             menu.php            myform.php
    myname.php          new.png             new.txt             test.php
    test.zip            [TPcodes]           uploadfile.php      [webalizer]
    welcome.png         [xampp]             
                     18 File(s)          123,694 bytes
                     8 Dir(s)            168,514,232,320 bytes free
    
    Last line of the output: 8 Dir(s) 168,514,232,320 bytes free
    Return value: 0
    

    The shell_exec() Function

    The shell_exec() function is identical to PHPs backtick operator. It executes the given command via shell and return the complete output as a string

    shell_exec(string$command):string|false|null

    The function returns a string containing the output from the executed command, false if the pipe cannot be established or null if an error occurs or the command produces no output.

    Example

    In the following code, we use shell_exec() function to obtain a list of files with “.php” as the extension in the current directory −

    <?php
       $output = shell_exec('dir *.php');
       echo "<pre>$output</pre>";
    ?>

    It will produce the following output −

    Volume in drive C has no label.
    Volume Serial Number is 7EE4-E492
    
    Directory of C:\xampp\htdocs
    
    10/26/2023  08:27 PM                73 hello.php
    10/12/2023  10:40 AM                61 homepage.php
    07/16/2015  09:02 PM               260 index.php
    10/12/2023  10:39 AM                49 menu.php
    09/25/2023  01:43 PM               338 myform.php
    10/12/2023  10:49 AM                51 myname.php
    10/26/2023  02:00 PM               369 test.php
    09/25/2023  01:42 PM               555 uploadfile.php
                   8 File(s)          1,756 bytes
                   0 Dir(s)           168,517,771,264 bytes free
    

    The exec() Function

    The exec() function executes the given command as a string argument.

    exec(string$command,array&$output=null,int&$result_code=null):string|false

    The $output parameter, if specified, is an array that will be filled with every line of output from the command.

    Example

    In this case, we use exec() function to call whoami command from inside the program. The whoami command returns the username.

    <?php
    
       // outputs the username that owns the running php/httpd process
       // (on a system with the "whoami" executable in the path)
       $output=null;
       $retval=null;
       exec('whoami', $output, $retval);
       echo "Returned with status $retval and output:\n";
       var_dump($output);
       
    ?>

    It will produce the following output −

    Returned with status 0 and output: array(1) 
    { [0]=> string(13) "gnvbgl3\mlath" }
    

    The passthru() Function

    The passthru() function executes an external program and display raw output. Though the passthru() function is similar to the exec() or system() function in that it executes a command, it should be used in their place when the output from the OS command is binary data which needs to be passed directly back to the browser.

    Example

    A PHP program that uses passthu() function to display the contents of system PATH environment variable

    passthru(string $command, int &$result_code = null): ?false
    <?php
       passthru ('PATH');
    ?>

    It will produce the following output −

    PATH=C:\Python311\Scripts\;C:\Python311\;C:\WINDOWS\system32;C:\WINDOWS;
    C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
    C:\WINDOWS\System32\OpenSSH\;C:\xampp\php;C:\Users\mlath\AppData\Local
    \Microsoft\WindowsApps;C:\VSCode\Microsoft VS Code\bin
    

    Backtick Operator

    PHP supports one execution operator: backticks (“). (they are not single-quotes!) PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned. Use of the backtick operator is identical to shell_exec().

    Example

    Take a look at the following example −

    <?php
       $output = `dir *.php`;
       echo "<pre>$output</pre>";
    ?>

    It will produce the following output −

    Volume in drive C has no label.
    Volume Serial Number is 7EE4-E492
    
    Directory of C:\xampp\htdocs
    
    10/26/2023  08:42 PM                61 hello.php
    10/12/2023  10:40 AM                61 homepage.php
    07/16/2015  09:02 PM               260 index.php
    10/12/2023  10:39 AM                49 menu.php
    09/25/2023  01:43 PM               338 myform.php
    10/12/2023  10:49 AM                51 myname.php
    10/26/2023  02:00 PM               369 test.php
    09/25/2023  01:42 PM               555 uploadfile.php
                   8 File(s)          1,744 bytes
                   0 Dir(s)           168,471,289,856 bytes free
    

    The backtick operator is disabled when shell_exec() is disabled.

  • PHP Variable Handling is_null() Function

    The PHP Variable Handling is_null() function is used to checks whether a variable is null. It returns true when the variable is null. It returns false if the variable contains any value. This function is useful for determining if a variable is empty.

    It helps prevent errors caused by missing values. It can run PHP 4, PHP 5, PHP 7, and PHP 8. It can be used to validate user input, database values, and other information. It is a simple and easy to use PHP function.

    Syntax

    Below is the syntax of the PHP Variable Handling is_null() function −

    boolis_null(mixed$value)

    Parameters

    This function accepts $value parameter which is the variable that you want to check.

    Return Value

    The is_null() function returns TRUE if the variable is null. And it returns FALSE if the variable has a value.

    PHP Version

    First introduced in core PHP 4.0.4, the is_null() function continues to function easily in PHP 5, PHP 7, and PHP 8.

    Example 1

    This program uses the PHP Variable Handling is_null() function to check whether a variable is null. If the variable is null, it will say “Variable is null”. Otherwise, it states “Variable is not null”. This is a simple example showing how is_null() works.

    <?php
       // Assigning null value
       $var = null; 
       if (is_null($var)) {
          echo "Variable is null"; 
       } else {
          echo "Variable is not null";
       }
    ?>

    Output

    Here is the outcome of the following code −

    Variable is null
    

    Example 2

    This program checks if an undefined variable is null. As the variable has not been declared, is_null() function returns true. This helps to prevent errors caused by missing variables. It provides the safe execution of PHP code.

    <?php
       if (is_null($undefinedVar)) {
          echo "Variable is null"; 
       } else {
          echo "Variable is not null";
       }
    ?>

    Output

    This will generate the below output −

    Variable is null
    

    Example 3

    This program checks if an array element is null using the is_null() function. It is useful for working with user input and database records. If the element is null, it will say “Element is null”. Otherwise, it will show “Element is not null”.

    <?php
       // Associative array with a null value
       $data = ["name" => "John", "age" => null]; 
       if (is_null($data["age"])) {
          echo "Element is null"; 
       } else {
          echo "Element is not null";
       }
    ?>

    Output

    This will create the below output −

    Element is null
  • 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:
  • PHP 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
  • PHP 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)
  • PHP 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->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->getMessage(). "in line no". $this->getLine();
          }
       }
       $num=125;
       try {
          if ($num>100 || $num<0)
          throw new myException("$num is invalid number");
          else
          echo "$num is a valid number";
       }
       catch (myException $m) {
          echo $m->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
  • PHP 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)
    }