Category: Advanced

  • CSPRNG

    The acronym CSPRNG stands for Cryptographically Secure Pseudorandom Number Generator. PHP function library includes many functions that generate random numbers. For example −

    • mt_rand() − Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand() − Seeds the Mersenne Twister Random Number Generator
    • rand() − Generate a random integer.

    Example

    The following code shows how you can use the function mt_rand() to generate random numbers −

    <?php
       # Generates random integer between the range
       echo "Random integer: " . rand(1,100) . PHP_EOL;
       # Generate a random value via the Mersenne Twister Random Number Generator
       echo "Random number: " . mt_rand(1,100);
    ?>

    It will produce the following output −

    Random integer: 45
    Random number: 86
    

    Note that the output may vary every time the code is executed. However, random numbers generated by these functions are not cryptographically safe, as it is possible to guess their outcome. PHP 7, introduced a couple of functions that generate secure random numbers.

    The following functions which are cryptographically secure, are newly added −

    • random_bytes() − Generates cryptographically secure pseudo-random bytes.
    • random_int() − Generates cryptographically secure pseudo-random integers.

    The random_bytes() Function

    random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

    stringrandom_bytes(int$length)

    Parameters

    • length − The length of the random string that should be returned in bytes.

    The function returns a string containing the requested number of cryptographically secure random bytes.

    If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If an invalid length of bytes is given, an Error will be thrown.

    Example

    Take a look at the following example −

    <?php
       $bytes = random_bytes(5);
       print(bin2hex($bytes));
    ?>

    It may produce the following output (it may differ every time) −

    6a85eec950
    

    The random_int() Function

    random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical.

    intrandom_int(int$min,int$max)

    Parameters

    • min − The lowest value to be returned, which must be PHP_INT_MIN or higher.
    • max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX.

    The function returns a cryptographically secure random integer in the range min to max, inclusive.

    If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If max is less than min, an Error will be thrown.

    Example

    Take a look at the following example −

    <?php
       print(random_int(100, 999));
       print("\n");
       print(random_int(-1000, 0));
    ?>

    It may produce the following output (it differs every time) −

    495
    -563
    

  • IntlChar

    In PHP7, a new IntlChar class has been introduced. It provides access to a number of utility methods that can be used to access information about Unicode characters. There are a number of static methods and constants in Intl class. They adhere closely to the names and behavior used by the underlying ICU (International Components for Unicode) library.

    Note that you need to enable the Intl extension in the PHP installation in your system. To enable, open php.ini file and uncomment (remove the leading semicolon from the line)

    extension=intl
    

    Some static functions from Intl class are explained with examples as below −

    IntlChar::charAge

    This function gets the “age” of the code point

    publicstaticIntlChar::charAge(int|string$codepoint):?array

    The “age” is the Unicode version when the code point was first designated (as a non-character or for Private Use) or assigned a character.

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::charage("\u{2603}"));
    ?>

    It will produce the following output −

    array(4) {
       [0]=>
       int(1)
       [1]=>
       int(1)
       [2]=>
       int(0)
       [3]=>
       int(0)
    }
    

    IntlChar::charFromName

    The charFromName() function finds Unicode character by name and return its code point value

    publicstaticIntlChar::charFromName(string$name,int$type=IntlChar::UNICODE_CHAR_NAME):?int

    The type parameter sets of names to use for the lookup. Can be any of these constants −

    • IntlChar::UNICODE_CHAR_NAME (default)
    • IntlChar::UNICODE_10_CHAR_NAME
    • IntlChar::EXTENDED_CHAR_NAME
    • IntlChar::CHAR_NAME_ALIAS
    • IntlChar::CHAR_NAME_CHOICE_COUNT

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::charFromName("LATIN CAPITAL LETTER A"));
       var_dump(IntlChar::charFromName("SNOWMAN"));
    ?>

    It will produce the following output −

    int(65)
    int(9731)
    

    IntlChar::charName

    The charName() function retrieves the name of a Unicode character

    publicstaticIntlChar::charName(int|string$codepoint,int$type=IntlChar::UNICODE_CHAR_NAME):?string

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::charName(".", IntlChar::UNICODE_CHAR_NAME));
       var_dump(IntlChar::charName("\u{2603}"));
    ?>

    It will produce the following output −

    string(9) "FULL STOP"
    string(7) "SNOWMAN"
    

    IntlChar::isalpha

    The isalpha() function determines whether the specified code point is a letter character. true for general categories “L” (letters).

    publicstaticIntlChar::isalpha(int|string$codepoint):?bool

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::isalpha("A"));
       var_dump(IntlChar::isalpha("1"));
    ?>

    It will produce the following output −

    bool(true)
    bool(false)
    

    The Intl class defines similar static methods such as isdigit(), isalnum(), isblank(), etc.

    IntlChar::islower

    The islower() function determines whether the specified code point has the general category “Ll” (lowercase letter).

    publicstaticIntlChar::islower(int|string$codepoint):?bool

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::islower("A"));
       var_dump(IntlChar::islower("a"));
    ?>

    It will produce the following output −

    bool(false)
    bool(true)
    

    Similarly, there are functions such as isupper(), istitle(), iswhitespace() etc.

    IntlChar::toupper

    The given character is mapped to its uppercase equivalent.

    publicstaticIntlChar::toupper(int|string$codepoint):int|string|null

    If the character has no uppercase equivalent, the character itself is returned.

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::toupper("A"));
       var_dump(IntlChar::toupper("a"));
    ?>

    It will produce the following output −

    string(1) "A"
    string(1) "A"

  • Filtered unserialize

    In PHP, the built-in function unserialize() is available from PHP version 4 onwards. With PHP 7, a provision to pass a list of allowed classes has been added. This allows the untrusted source to be filtered out. The unserialze() function unserializes the data from only the trusted classes.

    In PHP, serialization means generation of a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure. The built-in serialize() function is used for this purpose.

    serialize(mixed $value): string

    The unserialze() function gives a PHP value from the serialized representation. From PHP 7 onwards, the unserialize() function follows the format below −

    unserialize(string $data, array $options = [ ]): mixed

    The $data parameter is the serialized string which you want to unserialize.

    The $options parameter has been newly introduced. It is an associative array of following keys −

    Sr.NoName & Description
    1allowed_classesan array of class names which should be accepted,orfalse to accept no classes,ortrue to accept all classes.Omitting this option is the same as defining it as true
    2max_depthThe maximum depth of structures permitted during unserialization.

    Example

    Take a look at the following example −

    <?php
       class MyClass { 
    
      var int $x;
      function __construct(int $x) {
         $this-&gt;x = $x;
      }
    } class NewClass {
      var int $y;
      function __construct(int $y) {
         $this-&gt;y = $y;
      }
    } $obj1 = new MyClass(10); $obj2 = new NewClass(20); $sob1 = serialize($obj1); $sob2 = serialize($obj2); // default behaviour that accepts all classes // second argument can be ommited. // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object $usob1 = unserialize($sob1 , ["allowed_classes" => true]); // converts all objects into __PHP_Incomplete_Class object except those of MyClass and NewClass $usob2 = unserialize($sob2 , ["allowed_classes" => ["MyClass", "NewClass"]]); echo $usob1->x . PHP_EOL; echo $usob2->y . PHP_EOL; ?>

    It will produce the following output −

    10
    20
    
  • 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-&gt;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-&gt;x;
    }; print($value->call(new A)); ?>
  • 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

  • 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 "&lt;p&gt;Hello {$_SERVER['PHP_AUTH_USER']}.&lt;/p&gt;";
      echo "&lt;p&gt;You entered {$_SERVER['PHP_AUTH_PW']} as your password.&lt;/p&gt;";
    } ?>

    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

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

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