The “use” Statement

13. Advanced

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 − You can also have groupped use declaration as follows − 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 − It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 − Open Compiler It will produce the following output −

October 10, 2024 / 0 Comments
read more

Expectations

13. Advanced

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 − Directive Default value Possible values zend.assertions 1 1 − generate and execute code (development mode)0 − generate code but jump around it at runtime-1 − do not generate code (production mode) assert.exception 0 1 − 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 Return Values FALSE if the assertion is false, TRUE otherwise. Example Take a look at the following example − It will produce the following output −

October 10, 2024 / 0 Comments
read more

CSPRNG

13. Advanced

The acronym CSPRNG stands for Cryptographically Secure Pseudorandom Number Generator. PHP function library includes many functions that generate random numbers. For example − Example The following code shows how you can use the function mt_rand() to generate random numbers − Open Compiler It will produce the following output − 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 − 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. Parameters 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 − Open Compiler It may produce the following output (it may differ every time) − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. The random_int() Function random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical. Parameters 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 − Open Compiler It may produce the following output (it differs every time) −

October 10, 2024 / 0 Comments
read more

IntlChar

13. Advanced

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) Some static functions from Intl class are explained with examples as below − IntlChar::charAge This function gets the “age” of the code point 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 − It will produce the following output − IntlChar::charFromName The charFromName() function finds Unicode character by name and return its code point value The type parameter sets of names to use for the lookup. Can be any of these constants − Example Take a look at the following example − It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. IntlChar::charName The charName() function retrieves the name of a Unicode character Example Take a look at the following example − It will produce the following output − IntlChar::isalpha The isalpha() function determines whether the specified code point is a letter character. true for general categories “L” (letters). Example Take a look at the following example − It will produce the following output − 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). Example Take a look at the following example − It will produce the following output − Similarly, there are functions such as isupper(), istitle(), iswhitespace() etc. IntlChar::toupper The given character is mapped to its uppercase equivalent. If the character has no uppercase equivalent, the character itself is returned. Example Take a look at the following example − It will produce the following output −

October 10, 2024 / 0 Comments
read more

Filtered unserialize()

13. Advanced

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.No Name & Description 1 allowed_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 2 max_depthThe maximum depth of structures permitted during unserialization. Example Take a look at the following example − Open Compiler It will produce the following output −

October 10, 2024 / 0 Comments
read more

Closure::call()

13. Advanced

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 − 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 − 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 − Open Compiler 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 − Open Compiler

October 10, 2024 / 0 Comments
read more

Swapping Variables

13. Advanced

PHP doesn’t 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 − Open Compiler It will produce the following output − 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” − Open Compiler It will produce the following output − You can also use the other arithmetic operators – subtraction (-), multiplication (*) and division (/) in a similar manner to perform swapping. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 − Open Compiler It will produce the following output − 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 − Open Compiler It will produce the following output −

October 10, 2024 / 0 Comments
read more

HTTP Authentication

13. Advanced

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. The string parameter is passed to the header() function. For example 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. 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. Example An example script fragment which would force client authentication on a page is as follows − Output When you visit the script in a browser, it pops up a dialog box as shown − 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.

October 10, 2024 / 0 Comments
read more

System Calls

13. Advanced

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. 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. It will produce the following output − The shell_exec() Function The shell_exec() function is identical to PHP’s backtick operator. It executes the given command via shell and return the complete output as a string 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 − It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. The exec() Function The exec() function executes the given command as a string argument. 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. It will produce the following output − 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 It will produce the following output − 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 − It will produce the following output − The backtick operator is disabled when shell_exec() is disabled.

October 9, 2024 / 0 Comments
read more

PHP is_null() Function

13. Advanced

PHP defines NULL as one of its special data types. It indicates that a certain variable has not been assigned a value any specific data type. It is a built-in constant in PHP and is used to indicate the intentional absence of any object or value. A variable can be explicitly assigned NULL or its value been set to null by using the unset() function. The is_null() Function PHP provides a Boolean function is_null() to check if a variable is indeed of NULL type. Example 1 If any variable is explicitly assigned NULL, obviously the is_null() function returns true. Open Compiler It will produce the following output − Example 2 If a variable with a certain value is unset, then too the is_null() function returns true, but with a warning Open Compiler It will produce the following output − Example 3 Similarly, if you just declare a variable, without assigning any value to it, the is_null() function returns true with a warning − Open Compiler It will produce the following output − Example 4 You can also use the equality operator (==) to check if a variable is NULL. Open Compiler It will produce the following output − Example 5 A null string “” is not considered equal to NULL. Hence, the is_null() function as well as the “==” operator return false. Take a look at the following example − Open Compiler It will produce the following output − Two other functions in PHP that are relevant to is_null() function are the isset() function and the empty() function. The isset() Function The isset() function determines if a variable is declared and is different than NULL. Example A variable that is assigned NULL is considered as unset. Open Compiler It will produce the following output − Note that a null character (“\0”) is not equivalent to the PHP null constant. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. The empty() Function The empty() function checks if a variable is considered to be empty. A variable is considered empty if it does not exist or if its value is NULL. empty() does not generate a warning if the variable does not exist. Example 1 Take a look at the following example − Open Compiler It will produce the following output − Example 2 The empty() function returns true if a variable is set to “0”, NULL, or is not set at all. Open Compiler It will produce the following output −

October 9, 2024 / 0 Comments
read more

Posts pagination

Previous 1 … 121 122 123 … 445 Next