Blog

  • PHP CSRF

    The acronym “CSRF” stands for Cross-Site Request Forgery. CSRF is an Internet exploit that involves a trusted website user issuing unauthorized commands. Providing adequate protection to a PHP web application against this attack can be achieved by taking the measures explained in this chapter.

    By default, the browser uses the “GET” request method to send data. This is commonly used as the exploit point in a CSRF. To inject commands into a specific website, the attacker employs HTML tags like “IMG.” For example, the url endpoint of a web application such as “/delete.php?empcode=1234” deletes account as passed from empcode parameter of a GET request. Now, if an authenticated user come across the following script in any other application.

    <img src="http://example.com/delete.php?empcode=1234" 
       width="0" height="0" border="0">

    Inadvertently causes the data related to empcode=1234 to be deleted.

    A common workaround for this problem is the use of CSRF tokens. A CSRF token is a string of random characters embedded into requests so that a web application can trust that a request has been received from an expected source as per the normal workflow.

    Steps to Implement CSRF

    The steps to implement CSRF token protection in PHP are as follows −

    • Begin the script by starting a new session.
    • Generate a token of random characters. You can use any of the several built-in function that PHP provides for generation of random string. Let use md5() function to obtain the hash value of uniqueid() function that generates a unique randome string.
    • Inside the HTML form to be provided for the user to submit the data, include a hidden file with its value as the random token generated in the above step.
    • The token can is then validated by the server against the user session after form submission to eliminate malicious requests.
    • You can also add another session variable whose value is the current time, and send an expiry time for the validation purpose.

    Example

    Here is the PHP code that implements CSRF token verification mechanism. The following script generates a token and embeds in a HTML form.

    <?php
       session_start();
       if(!isset($_SESSION["csrf_token"])) {
       
          // No token present, generate a new one
          $token = md5(uniqid(rand(), true));
          $_SESSION["csrf_token"] = $token;
    	  
       } else {
       
          // Reuse the token
          $token = $_SESSION["csrf_token"];        
       }
    ?><html><body><form method="get" action="test.php"><input type="text" name="empcode" placeholder="empcode" /><input type="hidden" name="csrf_token" value="<?php echo $token;?>" /><input type="submit" /></form></body></html>

    The form is submitted to “test.php” script as below −

    <?php
       session_start();
       echo "hello";
       if ($_GET["csrf_token"] == $_SESSION["csrf_token"]) {
    
          // Reset token
          echo $_GET["csrf_token"] . "<br>";
          echo $_SESSION["csrf_token"] . "<br>";
          echo "<h3>CSRF token validation successful. Proceed to further action</h3>";
       } else {
          echo "<h3>CSRF token validation failed</h3>";
       }
    ?>

    It will produce the following output −

    PHP Csrf

    To simulate the failure of CSRF validation, open the inspect tool of the browser, edit the value in the hidden field manually and submit the form to see that the tokens dont match leading to the validation failure.

  • PHP PEAR

    PEAR is an acronym for PHP Extension and Application Repository. It is a repository of PHP packages or extensions. You can freely incorporate any of these extensions from PEAR in your code. The PEAR project was established by Stig S. Bakken in 1999.

    Most of the precompiled distributions of PHP such as XAMPP already have PEAR bundled with it. If not, you can install PEAR by downloading go-pear.phar file from https://pear.php.net/go-pear.phar and run

    php go-pear.phar
    

    In a Windows Command Prompt to start the installation.

    Based on your responses to the setup steps, the PEAR Package Manager will be installed in the path, specified during installation.

    You can then add that installation path to your PATH environment. Either do this manually (Start > Control Panel > System > Environment) or run (double-click) the newly generated PEAR_ENV.reg that’s now found in the PHP source directory.

    You can now access the PEAR Package Manager by running the command −

    C:\xampp\php>pear 
    

    In a Windows Command Prompt.

    You will get the list of PEAR commands as follows −

    C:\xampp\php>pear
    Commands:
    build                  Build an Extension From C Source
    bundle                 Unpacks a Pecl Package
    channel-add            Add a Channel
    channel-alias          Specify an alias to a channel name
    channel-delete         Remove a Channel From the List
    channel-discover       Initialize a Channel from its server
    channel-info           Retrieve Information on a Channel
    channel-login          Connects and authenticates to remote channel server
    channel-logout         Logs out from the remote channel server
    channel-update         Update an Existing Channel
    clear-cache            Clear Web Services Cache
    config-create          Create a Default configuration file
    config-get             Show One Setting
    config-help            Show Information About Setting
    config-set             Change Setting
    config-show            Show All Settings
    convert                Convert a package.xml 1.0 to package.xml 2.0 format
    cvsdiff                Run a "cvs diff"for all files in a package
    cvstag                 Set CVS Release Tag
    download               Download Package
    download-all           Downloads each available package from the default channel
    info                   Display information about a package
    install                Install Package
    listList Installed Packages In The Default Channel
    list-all               List All Packages
    list-channels          List Available Channels
    list-files             List Files In Installed Package
    list-upgrades          List Available Upgrades
    login                  Connects and authenticates to remote server [Deprecated in favor of channel-login]
    logout                 Logs out from the remote server [Deprecated in favor of channel-logout]
    makerpm                Builds an RPM spec file from a PEAR package
    package                Build Package
    package-dependencies   Show package dependencies
    package-validate       Validate Package Consistency
    pickle                 Build PECL Package
    remote-info            Information About Remote Packages
    remote-listList Remote Packages
    run-scripts            Run Post-Install Scripts bundled with a package
    run-tests              Run Regression Tests
    search                 Search remote package database
    shell-test             Shell Script Test
    sign                   Sign a package distribution file
    svntag                 Set SVN Release Tag
    uninstall              Un-install Package
    update-channels        Update the Channel List
    upgrade                Upgrade Package
    upgrade-all            Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]

    Installing packages with PEAR is so easy. One way to find packages, is using the official PEAR site https://pear.php.net/packages.php and then run

    pear install <package-name>

    The next step is to use the PEAR package in your code. To do that, you should include the main PHP script of the package in your program with include, require, include_once or require_once statements.

    <?php
       include "PEARPACKAGE.php";
       . . . . . 
       // rest of the code
       . . . . . 
    ?>

    A newer PHP package manager called Composer is an alternative available for managing packages for a PHP project. Composer also supports the installation of PEAR packages. Composer is preferred by many instead of PEAR for PHP package distribution.

  • PHP Removed Extensions & SAPIs

    With each new version of PHP, new functionality is added and at the same time certain obsolete functionality is removed. PHP version 7 is a major version when a number of PHP extensions and SAPIs (Server-side Application Programming Interface) were removed. In the subsequent PHP 8 version also, a few more extensions have been removed.

    In PHP, an extension is a library or plugin, written in C/C++, and compiled into shared libraries so that can be loaded into the PHP interpreter. Once the PHP interpreter starts, the functions in the extension are available to PHP scripts.

    The extensions are periodically removed because they are either no longer maintained or have been replaced with more modern alternatives. Coinciding with PHP 7 for example, the ereg extension was replaced with the preg extension, and the mssql extension was replaced with the PDO_MSSQL extension.

    Removed Extensions

    The following extensions have been removed with effect from PHP 7 −

    • ereg extension replaced by preg
    • mssql extension replaced by pdo_mssql
    • mysql extension mysqli
    • sybase_ct replaced by pdo_sybase

    The following extensions have been removed from PHP 8 onwards −

    • Mcrypt − The Mcrypt extension was used for encryption and decryption, but it has been deprecated since PHP 7.1 and removed in PHP 8 due to security vulnerabilities.
    • MDB2 − The MDB2 extension, earlier used for accessing MDB database files, is removed in PHP 8 due to lack of maintenance.
    • Ming − As Flash is not popular nowadays, the Ming extension, used for generating flash content, has been deprecated since PHP 5.5 and removed in PHP 8.
    • Phar Data − The Phar Data extension was used for accessing data within PHAR archives, but it has been removed in PHP 8 as there are other methods for accessing PHAR data.
    • SNMP − Because it is not being maintained, the SNMP extension has been removed in PHP 8.
    • Tidy − Since new libraries for HTML validation have been added, the Tidy extension was removed in PHP.
    • Tokenizer − The Tokenizer extension was also removed in PHP 8 for the same reason.
    • cURL − The cURL extension was removed in PHP 8.1, as it was no longer maintained.

    Removed SAPIs

    SAPI stands for Server-side Application Programming Interface in PHP. The SAPI is responsible for translating PHP code into something that the web server can understand. It parses the PHP code and calls the appropriate web server functions. The web server then generates an HTTP response that is sent back to the client.

    The following SAPIs (Server-side Application Programming Interfaces) have been removed from PHP 7 onwards −

    • aolserver
    • apache
    • apache_hooks
    • apache2filter
    • caudium
    • cgi
    • cgi-fcgi
    • fastcgi
    • isapi
    • litespeed
    • nsapi
    • pwsapi
    • router
    • thttpd
    • uwsgi
    • webserver
    • apache2filter
    • continuity
    • isapi
    • milter
    • nsapi
    • pi3web
    • roxen
    • thttpd
    • tux
    • webjames
  • PHP Deprecated Features

    As some new features are added with each new version, some features are also removed as they are deemed to be obsolete. In this chapter, we have a look at deprecated features after PHP version 5.

    Deprecated in PHP Ver 7

    PHP 4 Style Constructors

    PHP 4 style Constructors are methods having same name as the class they are defined in, are now deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes implementing a __construct() method are unaffected.

    Example

    Take a look at the following example −

    <?php
       class A {
          function A() {
             print('Style Constructor');
          }
       }
    ?>

    It produces the following output on the browser −

    Deprecated: Methods with the same name as their class will not be 
    constructors in a future version of PHP; A has a deprecated constructor in...
    

    Static Calls to Non-static Methods

    Static calls to non-static methods are deprecated, and may be removed in the future.

    Example

    Take a look at the following example −

    <?php
       class A {
          function b() {
             print('Non-static call');
          }
       }
       A::b();
    ?>

    It produces the following output on the browser −

    Deprecated: Non-static method A::b() should not be called statically in...
    Non-static call
    

    password_hash() salt option

    The salt option for the password_hash() function has been deprecated so that the developers do not generate their own (usually insecure) salts. The function itself generates a cryptographically secure salt, when no salt is provided by the developer – thus custom salt generation is not required any more.

    capture_session_meta SSL context option

    The capture_session_meta SSL context option has been deprecated. SSL metadata is now used through the stream_get_meta_data() function.

    ext/mcrypt

    The mcrypt extension has been deprecated in favour of OpenSSL.

    Unquoted Strings

    Unquoted strings that are non-existent global constants are taken to be strings of themselves. This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.

    The __autoload() Method

    The __autoload() method has been deprecated because it is inferior to spl_autoload_register() (due to it not being able to chain autoloaders), and there is no interoperability between the two autoloading styles.

    The create_function() Function

    Given the security issues of this function has now been deprecated. The preferred alternative is to use anonymous functions.

    The each() Function

    This function causes implementation issues for some language changes. It has therefore been deprecated.

    Case-Insensitive Constants

    The declaration of case-insensitive constants has been deprecated. Passing true as the third argument to define() will now generate a deprecation warning.

    The (real) and is-real() Function

    The (real) cast is deprecated, use (float) instead. The is_real() function is also deprecated, use is_float() instead.

    The “parent” Leyword

    Using parent inside a class without a parent is deprecated, and will throw a compile-time error in the future. Currently an error will only be generated if/when the parent is accessed at run-time.

    Deprecated in PHP Ver 8

    If a parameter with a default value is followed by a required parameter, the default value has no effect. This is deprecated as of PHP 8.0.0 and can generally be resolved by dropping the default value, without a change in functionality −

    <?php
       function test($a = [], $b) {}  // Before
       function test($a, $b) {}      // After
    ?>

    One exception to this rule are parameters of the form Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, but it is recommended to use an explicit nullable type instead −

    <?php
       function test(A $a = null, $b) {} 	// Still allowed
       function test(?A $a, $b) {}         // Recommended
    ?>

    Calling get_defined_functions() with exclude_disabled explicitly set to false is deprecated and no longer has an effect. get_defined_functions() will never include disabled functions.

    Sort comparison functions that return true or false will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.

    <?php
       // Replace
       usort($array, fn($a, $b) => $a > $b);
       // With
       usort($array, fn($a, $b) => $a <=> $b);
    ?>

    Implicit Incompatible float to int Conversions

    The implicit conversion of float to int which leads to a loss in precision is now deprecated. This affects array keys, int type declarations in coercive mode, and operators working on ints.

    Calling a Static Element on a Trait

    Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.

    Date Functions

    date_sunrise() and date_sunset() have been deprecated. Use date_sun_info() instead.

    strptime() has been deprecated. Use date_parse_from_format() instead (for locale-independent parsing), or IntlDateFormatter::parse() (for locale-dependent parsing).

    strftime() and gmstrftime() have been deprecated. You can use date() instead (for locale-independent formatting), or IntlDateFormatter::format() (for locale-dependent formatting).

    Dynamic Properties

    The creation of dynamic properties is deprecated. Instead, use stdClass that allows dynamic properties.

  • PHP Integer Division

    PHP has introduced a new function intdiv(), which performs integer division of its operands and return the division as int.

    The intdiv() function returns integer quotient of two integer parameters. If “a/b” results in “c” as division and “r” as remainder such that −

    a=b*c+r
    

    In this case, intdiv(a,b) returns r −

    intdiv(int$x,int$y):int

    The $x and $y are the numerator and denominator parts of the division expression. The intdiv() function returns an integer. The return value is positive if both parameters are positive or both parameters are negative.

    Example 1

    If numerator is < denominator, the intdiv() function returns “0”, as shown below −

    <?php
       $x=10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
       $r=intdiv($y, $x);
       echo "intdiv(" . $y . "," . $x . ") = " . $r;
    ?>

    It will produce the following output −

    intdiv(10,3) = 3
    intdiv(3,10) = 0
    

    Example 2

    In the following example, the intdiv() function returns negative integer because either the numerator or denominator is negative.

    <?php
       $x=10;
       $y=-3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
       $x=-10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    ?>

    It will produce the following output −

    intdiv(10,-3) = -3
    intdiv(-10,3) = -3
    

    Example 3

    The intdiv() function returns a positive integer in the case of numerator and denominator both being positive or both being negative.

    <?php
       $x=10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=-10;
       $y=-3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r ;
    ?>

    It will produce the following output −

    intdiv(10,3) = 3
    intdiv(-10,-3) = 3
    

    Example 4

    In the following example, the denominator is “0”. It results in DivisionByZeroError exception.

    <?php
       $x=10;
       $y=0; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    ?>

    It will produce the following output −

    PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero in hello.php:4
  • PHP The “use” Statement

    The “use” keyword in PHP is found to be associated with multiple purposes, such as aliasing, inserting traits and inheriting variables in closures.

    Aliasing

    Aliasing is accomplished with the use operator. It allows you to refer to an external fully qualified name with an alias or alternate name.

    Example

    Take a look at the following example −

    useMy\namespace\myclassas Another;$obj=newAnother;

    You can also have groupped use declaration as follows −

    use some\namespace\{ClassA, ClassB, ClassC asC};usefunction some\namespace\{fn_a, fn_b, fn_c};useconst some\namespace\{ConstA, ConstB, ConstC};

    Traits

    With the help of use keyword, you can insert a trait into a class. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own.

    Example

    Take a look at the following example −

    <?php
       trait mytrait {
          public function hello() {
             echo "Hello World from " . __TRAIT__ .;
          }
       }
    
       class myclass {
          use mytrait;
       }
    
       $obj = new myclass();
       $obj->hello();
    ?>

    It will produce the following output −

    Hello World from mytrait
    

    Closures

    Closure is also an anonymous function that can access variables outside its scope with the help of the “use” keyword.

    Example

    Take a look at the following example −

    <?php
       $maxmarks=300;
       $percent=function ($marks) use ($maxmarks) {
          return $marks*100/$maxmarks;
       };
       $m = 250;
       echo "marks=$m percentage=". $percent($m);
    ?>

    It will produce the following output −

    marks=250 percentage=83.333333333333
  • PHP Expectations

    Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails.

    assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested.

    Configuration Directives for assert()

    The following table lists down the configuration directives for the assert() function −

    DirectiveDefault valuePossible values
    zend.assertions11 − generate and execute code (development mode)0 − generate code but jump around it at runtime-1 − do not generate code (production mode)
    assert.exception01 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided.0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

    Parameters

    • Assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.
    • Description − An optional description that will be included in the failure message, if the assertion fails.
    • Exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled.

    Return Values

    FALSE if the assertion is false, TRUE otherwise.

    Example

    Take a look at the following example −

    <?php
       ini_set('assert.exception', 1);
       class CustomError extends AssertionError {}
       assert(false, new CustomError('Custom Error Message!'));
    ?>

    It will produce the following output −

    PHP Fatal error:  Uncaught CustomError: Custom Error Message! In test.php:6
  • PHP 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
  • PHP 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"
  • PHP 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->x = $x;
          }
       }
       class NewClass {
          var int $y;
          function __construct(int $y) {
             $this->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