Core PHP vs Frameworks ”; Previous Next PHP is by far the most popular server-side programming language for web application development, with nearly 75% of websites using PHP either in its core form or one of the PHP frameworks available. To make a choice between using “core PHP” or frameworks for web development, we need to understand the pros and cons of both. To give a simple analogy, developing a web application purely with core PHP is like solving a mathematical problem manually by writing down each step on the paper. On the other hand, using a framework is similar to using tools such as a calculator to solve a problem. Just as a calculator, the frameworks are useful tools for rapid application development. Core PHP vs Frameworks – Pros and Cons A web framework, especially a PHP framework is a collection of one or more PHP libraries and classes. It provides a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code scratch. It provides a reusable software environment that quickly builds a minimal working template application. Developing a web application purely in core PHP has its own advantages and disadvantages − It gives the developer better control and flexibility. At the same time, for a larger application developed with core PHP only can become unwieldy, difficult to manage and maintain. Now, let”s turn to pros and cons of using PHP Frameworks − A PHP framework such as Symfony, Laravel or Yii offers a more standardized approach towards web application development. With most of the routine and repetitive part handled by the framework, the developer can concentrate more on the application logic. Hence, there is lesser time wasted in debugging. On the other hand, a framework is not as flexible compared to core PHP. The skeleton template of the application is readily made available by the framework, leaving the developer to customize the functionality only within the scope defined by the framework. The MVC Architecture Most of the web application frameworks employ the MVC (Model, View and Controller) architecture, which makes it a lot easier to write quality, robust code, by separating the logic from the style. If you wish to use the core PHP features for your application development, you are free to adopt an object oriented approach or a modular approach, whichever suits you. Built-in Security Measures PHP frameworks offer built-in security measures to be incorporated in a web applications. If you choose to develop an application with core PHP, you will have to provide the security measures explicitly. Most of the frameworks however have a few external dependencies, which may leave the application rather vulnerable, as compared to a core PHP application which is a self-contained solution. A framework-based application may be a little slow when it comes to performance, as compared to core PHP application, especially for a smaller application. Comparison: Core PHP vs Frameworks The comparison between the two can be summarized as follows − For smaller applications, core PHP is preferrable over framework. Framework offers rapid development and code reusability. Frameworks are less flexible. Using core PHP features, the developer has complete control. For large applications, the MVC architecture is helpful. Frameworks offer integrated authorization and authentication support. In a core PHP application, the security rules need to be explicitly defined. Print Page Previous Next Advertisements ”;
Category: php
PHP – JSON
PHP â JSON ”; Previous Next 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 Constant Values JSON_HEX_TAG 1 JSON_HEX_AMP 2 JSON_HEX_APOS 4 JSON_HEX_QUOT 8 JSON_FORCE_OBJECT 16 JSON_NUMERIC_CHECK 32 JSON_UNESCAPED_SLASHES 64 JSON_PRETTY_PRINT 128 JSON_UNESCAPED_UNICODE 256 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.No Constant & Meaning 1 JSON_ERROR_NONE No error has occurred 2 JSON_ERROR_DEPTH The maximum stack depth has been exceeded 3 JSON_ERROR_STATE_MISMATCH Invalid or malformed JSON 4 JSON_ERROR_CTRL_CHAR Control character error, possibly incorrectly encoded 5 JSON_ERROR_SYNTAX Syntax error 6 JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded 7 JSON_ERROR_RECURSION One or more recursive references in the value to be encoded 8 JSON_ERROR_INF_OR_NAN One or more NAN or INF values in the value to be encoded 9 JSON_ERROR_UNSUPPORTED_TYPE A value of a type that cannot be encoded was given 10 JSON_ERROR_INVALID_PROPERTY_NAME A property name that cannot be encoded was given 11 JSON_ERROR_UTF16 Malformed 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) } Print Page Previous Next Advertisements ”;
PHP – Filters
PHP â Filters ”; Previous Next It is important that the input data received in the form of client request is validated before processing in a PHP application. To perform input validation, the filter extension in PHP provides a number of filter functions, backed up by predefined filter constants and flags. The filter extension of PHP library also helps in sanitizing the input received by either GET or POST methods. The filter extension is a powerful feature that helps prevention of security vulnerabilities, such as SQL injection and cross-site scripting. The extension has two types of filters − Validation Filters Validation filters check if the data meets certain criteria. For example, you want to ensure that the user has correctly input an email field in the HTML form. The FILTER_VALIDATE_EMAIL will determine if the data is a valid email address. The validation filters, however, will not change the data itself. Sanitization Filters Sanitization refers to the process of removing undesired characters from the input. Hence, it may alter the data by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain, without performing validation. Filter Flags The filter extension in PHP defines a number of filter flags as follows − Sr.No ID & Description 1 FILTER_FLAG_STRIP_LOW Strips characters that have a numerical value <32. 2 FILTER_FLAG_STRIP_HIGH Strips characters that have a numerical value >127. 3 FILTER_FLAG_STRIP_BACKTICK Strips backtick characters. 4 FILTER_FLAG_ALLOW_FRACTION Allows a period (.) as a fractional separator in numbers. 5 FILTER_FLAG_ALLOW_THOUSAND Allows a comma (,) as a thousands separator in numbers. 6 FILTER_FLAG_ALLOW_SCIENTIFIC Allows an e or E for scientific notation in numbers. 7 FILTER_FLAG_NO_ENCODE_QUOTES If this flag is present, single (”) and double (“) quotes will not be encoded. 8 FILTER_FLAG_ENCODE_LOW Encodes all characters with a numerical value <32. 9 FILTER_FLAG_ENCODE_HIGH Encodes all characters with a numerical value >127. 10 FILTER_FLAG_ENCODE_AMP Encodes ampersands (&). 11 FILTER_NULL_ON_FAILURE Returns null for unrecognized values. 12 FILTER_FLAG_ALLOW_OCTAL Regards inputs starting with a zero (0) as octal numbers. 13 FILTER_FLAG_ALLOW_HEX Regards inputs starting with 0x or 0X as hexadecimal numbers. 14 FILTER_FLAG_EMAIL_UNICODE Allows the local part of the email address to contain Unicode characters. 15 FILTER_FLAG_IPV4 Allows the IP address to be in IPv4 format. 16 FILTER_FLAG_IPV6 Allows the IP address to be in IPv6 format. 17 FILTER_FLAG_NO_PRIV_RANGE Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. 18 FILTER_FLAG_NO_RES_RANGE Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4. Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10. 19 FILTER_FLAG_GLOBAL_RANGE Fails validation for non global IPv4/IPv6 ranges 20 FILTER_FLAG_SCHEME_REQUIRED Requires the URL to contain a scheme part. 21 FILTER_FLAG_HOST_REQUIRED Requires the URL to contain a host part. 22 FILTER_FLAG_PATH_REQUIRED Requires the URL to contain a path part. 23 FILTER_FLAG_QUERY_REQUIRED Requires the URL to contain a query string. 24 FILTER_REQUIRE_SCALAR Requires the value to be scalar. 25 FILTER_REQUIRE_ARRAY Requires the value to be an array. 26 FILTER_FORCE_ARRAY If the value is a scalar, it is treated as array with the scalar value as only element. Filter Functions The filter extension includes the following filter functions − Sr.No ID & Description 1 filter_has_var() Checks if variable of specified type exists 2 filter_id() Returns the filter ID belonging to a named filter 3 filter_input_array() Gets external variables and optionally filters them 4 filter_input () Gets a specific external variable by name and filters it 5 filter_list() Returns a list of all supported filters 6 filter_var_array() Gets multiple variables and optionally filters them 7 filter_var() Filters a variable with a specified filter Predefined Constants The above functions use one parameter called input_type which is one of the predefined enumerated constants representing how the input has been provided to the PHP script for filtering purpose. Constant Types INPUT_POST (int) POST Variables INPUT_GET (int) GET Variables INPUT_COOKIE (int) COOKIE Variables INPUT_ENV (int) ENV Variables INPUT_SERVER (int) SERVER Variables INPUT_SESSION (int) SESSION Variables INPUT_REQUEST (int) REQUEST Variables filter_has_var() function The filter_has_var() function checks if variable of specified type exists. filter_has_var(int $input_type, string $var_name): bool The input_type is one of predefined constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV; where as the var_name parameter is the name of a variable to check. The function returns true on success or false on failure. Example Visit the following PHP script on the XAMPP server. <?php if (!filter_has_var(INPUT_GET, “email”)) { echo(“Email not found”); } else { echo(“Email found”); } ?> It will produce the following output − Visit http://localhost/[email protected] Email found filter_input() function
PHP – Hashing
PHP â Hashing ”; Previous Next 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 − 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 Print Page Previous Next Advertisements ”;
PHP – Encryption
PHP â Encryption ”; Previous Next 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.No Parameter & Description 1 data The plaintext message data to be encrypted. 2 cipher_algo The cipher method. 3 passphrase The passphrase. If the passphrase is shorter than expected, padded with NULL characters; if the passphrase is longer than expected, it is truncated. 4 options options is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING. 5 iv A non-NULL Initialization Vector. 6 tag The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM). 7 aad Additional authenticated data. 8 tag_length The 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: Print Page Previous Next Advertisements ”;
PHP – Form Email/URL
PHP – Form Email/URL ”; Previous Next PHP provides two alternatives for validating the form data items which are strings but are expected to be a representation of Email ID or a URL. One way to check the form element contains email/URL is with the use of RegEx (regular expressions), and the other, more convenient approach is to use filter_var() function. Let us apply both these methods and validate email and URL submitted by a form to a PHP script. The HTML Form used for this chapter is as follows − <h1>Email and URL Validation</h1> <form action=”hello.php” method=”POST”> <p><label for=”email”>Enter your email:</label> <input type=”text” id=”email” name=”email”></p> <p><label for=”URL”>Enter your website<label> <input type = “text” id=”URL” name=”url”></p> <input type=”submit”> </form> Validation with Regex PHP’s built-in function library includes the preg_match() function that performs a regular expression match. preg_match( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0 ): int|false This function searches subject for a match to the regular expression given in pattern. preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or false on failure. A valid email ID should satisfy the following regular expression − “/^([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@([a-z0-9-]+.)+[a-z]{2,6}$/ix” Similarly, a valid URL should satisfy the following regular expression − “/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i” The following function returns “1” or “0” if the string is a valid email ID. function checkemail($str) { return (!preg_match(“/^([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@([a-z0-9-]+.)+[a-z]{2,6}$/ix”, $str)) ? FALSE : TRUE; } Example Let us use the checkmail() function to check whether the email field in the above HTML is valid or not, with the help of following PHP code − <?php function checkemail($str) { return (!preg_match(“/^([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@ ([a-z0-9-]+.)+[a-z]{2,6}$/ix”, $str)) ? FALSE : TRUE; } if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $email = $_POST[”email”]; if(!checkemail($email)){ echo “Invalid email address.”; } else { echo “Valid email address.”; } } ?> The HTML form is rendered as below − Test the PHP code by entering valid/invalid email string in the email field. The following checkURL() function checks if a string represents a valid or invalid URL, and returns “1 or “0”. function checkURL($str) { return (!preg_match(“/b(?:(?:https?|ftp)://|www.) [-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i”, $str)) ? FALSE : TRUE; } Example The URL field extracted from the $_POST array is given as argument to the above function. <?php function checkURL($str) { return (!preg_match(“/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;] *[-a-z0-9+&@#/%=~_|]/i”, $str)) ? FALSE : TRUE; } if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $url = $_POST[”url”]; if(!checkURL($url)){ echo “Invalid URL.”; } else { echo “Valid URL.”; } } ?> You can test the above code by entering URL string in the URL field of the above form. Using filter_var() function The built-in filter_var() function filters a variable with a specified filter. filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed Depending on the enumerated filter ID as the value of $filter parameter, the $value parameter is checked and the function returns the filtered data, or false if the filter fails. There are various predefined filter ID constants available − Sr.No ID & Description 1 FILTER_VALIDATE_BOOL Returns true for “1”, “true”, “on” and “yes”. Returns false otherwise. 2 FILTER_VALIDATE_DOMAIN Validates whether the domain name label lengths are valid. 3 FILTER_VALIDATE_EMAIL Validates whether the value is a valid e-mail address. 4 FILTER_VALIDATE_IP Validates value as IP address 5 FILTER_VALIDATE_URL Validates value as URL Example The following PHP script validates the email and URL data submitted by the HTML for above − <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $email = $_POST[”email”]; $url = $_POST[”url”]; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo “Invalid email format and please re-enter valid emailn”; } else echo “Email entered is in valid formatn”; if (!filter_var($url, FILTER_VALIDATE_URL)) { echo “Invalid URL format and please re-enter valid URLn”; } else echo “URL entered is in valid formatn”; } ?> You can test the performance of the above script by entering valid/invalid email/URL. Print Page Previous Next Advertisements ”;
PHP – HTTP Authentication
PHP â HTTP Authentication ”; Previous Next 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 − 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. Print Page Previous Next Advertisements ”;
PHP – Inheritance
PHP â Inheritance ”; Previous Next Inheritance is one of the fundamental principles of object-oriented programming methodology. Inheritance is a software modelling approach that enables extending the capability of an existing class to build new class instead of building from scratch. PHP provides all the functionality to implement inheritance in its object model. Incorporating inheritance in PHP software development results in code reuse, remove redundant code duplication and logical organization. Imagine that you need to design a new class whose most of the functionality already well defined in an existing class. Inheritance lets you to extend the existing class, add or remove its features and develop a new class. In fact, PHP has the “extends” keyword to establish inheritance relationship between existing and new classes. class newclass extends oldclass { … … } Inheritance comes into picture when a new class (henceforth will be called inherited class, sub class, child class, etc.) possesses “IS A” relationship with an existing class (which will be called base class, super class, parent class, etc.). In PHP, when a new class is defined by extending another class, the subclass inherits the public and protected methods, properties and constants from the parent class. You are free to override the functionality of an inherited method, otherwise it will retain its functionality as defined in the parent class. Example Take a look at the following example − <?php class myclass { public function hello() { echo “Hello from the parent class” . PHP_EOL; } public function thanks() { echo “Thank you from parent class” . PHP_EOL; } } class newclass extends myclass { public function thanks() { echo “Thank you from the child class” . PHP_EOL; } } # object of parent class $obj1 = new myclass; $obj1->hello(); $obj1->thanks(); # object of child class $obj2 = new newclass; $obj2->hello(); $obj2->thanks(); ?> It will produce the following output − Hello from the parent class Thank you from parent class Hello from the parent class Thank you from the child class As mentioned before, the child class inherits public and protected members (properties and methods) of the parent. The child class may introduce additional properties or methods. In the following example, we use the Book class as the parent class. Here, we create an ebook class that extends the Book class. The new class has an additional property â format (indicating ebookâs file format â EPUB, PDF, MOBI etc). The ebook class defines two new methods to initialize and output the ebbok data â getebook() and dispebook() respectively. Example The complete code of inheritance example is given below − <?php class Book { /* Member variables */ protected int $price; protected string $title; public function getbook(string $param1, int $param2) { $this->title = $param1; $this->price = $param2; } public function dispbook() { echo “Title: $this->title Price: $this->price n”; } } class ebook extends Book { private string $format; public function getebook(string $param1, int $param2, string $param3) { $this->title = $param1; $this->price = $param2; $this->format = $param3; } public function dispebook() { echo “Title: $this->title Price: $this->pricen”; echo “Format: $this->format n”; } } $eb = new ebook; $eb->getebook(“PHP Fundamentals”, 450, “EPUB”); $eb->dispebook(); ?> The browser output is as shown below − Title: PHP Fundamentals Price: 450 Format: EPUB If you take a closer look at the getebook() function, the first two assignment statements are in fact there getbook() function, which the ebook class has inherited. Hence, we can call it with parent keyword and scope resolution operator. Change the getebook() function code with the following − public function getebook(string $param1, int $param2, string $param3) { parent::getbook($param1, $param2); $this->format = $param3; } Similarly, the first echo statement in dispebook() function is replaced by a call to the dispbook() function in parent class − public function dispebook() { parent::dispbook(); echo “Format: $this->format<br/>”; } Constructor in Inheritance The constructor in the parent class constructor is inherited by the child class but it cannot be directly called in the child class if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. Example Take a look at the following example − <?php class myclass{ public function __construct(){ echo “This is parent constructor”. PHP_EOL; } } class newclass extends myclass { public function __construct(){ parent::__construct(); echo “This is child class destructor” . PHP_EOL; } } $obj = new newclass(); ?> It will produce the following output − This is parent constructor This is child class destructor However, if the child does not have a constructor, then it may be inherited from the parent class just like a normal class method (if it was not declared as private). Example Take a look at the following example − <?php class myclass{ public function __construct(){ echo “This is parent constructor”. PHP_EOL; } } class newclass extends myclass{ } $obj = new newclass(); ?> It will produce the following output − This is parent constructor PHP doesnât allow developing a class by extending more than one parents. You can have hierarchical inheritance, wherein class B extends class A, class C extends class B, and so on. But PHP doesnât support multiple inheritance where class C tries to extend both class A and class B. We can however extend one class and implement one or more interfaces. We shall learn about interfaces in one of the subsequent chapters. Print Page Previous Next Advertisements ”;
PHP – Design Patterns
PHP – Design Patterns ”; Previous Next In the theory of software engineering, the term “Design patterns” generally refers to a reusable solution that can be used as a template for developing applications to address commonly occurring problems. You can consider the software design patterns as formalized best practices when developing software solutions. Most of the standard design patterns can be very effectively implemented in developing applications in PHP. In this chapter, we shall learn how to apply some of the popular design patterns in developing PHP applications. Singleton Pattern The singleton design pattern is useful when you want to restrict the instantiation of an object of a certain class to only one instance. The name “singleton pattern” comes from the concept of singleton in Mathematics. Singleton pattern ensures that there will be only one instance, having a global access to it throughout the application. Typical application of singleton pattern is creation of a database connection object, which must be created once in the lifetime of an application. Example In the following code, the DataBaseConnector class can be instantiated only once, otherwise a message that disallows duplicate object will be issued. <?php class DataBaseConnector { private static $obj; private final function __construct() { echo __CLASS__ . ” object created for first time “. PHP_EOL; } public static function getConnect() { if (!isset(self::$obj)) { self::$obj = new DataBaseConnector(); return self::$obj; } else { echo “connection object could not be created again” . PHP_EOL; } } } $obj1 = DataBaseConnector::getConnect(); $obj2 = DataBaseConnector::getConnect(); var_dump($obj1 == $obj2); ?> It will produce the following output − DataBaseConnector object created for first time connection object could not be created again bool(false) Factory Pattern This is one of the most commonly used design patterns. In this pattern, you don’t declare the object of the desired class directly, but another class is provided whose static method creates the required object. Example The following example demonstrates how factory design pattern works − <?php class Automobile { private $bikeMake; private $bikeModel; public function __construct($make, $model) { $this->bikeMake = $make; $this->bikeModel = $model; } public function getMakeAndModel() { return $this->bikeMake . ” ” . $this->bikeModel; } } class AutomobileFactory { public static function create($make, $model) { return new Automobile($make, $model); } } $pulsar = AutomobileFactory::create(”ktm”, ”Pulsar”); print_r($pulsar->getMakeAndModel()); ?> It will produce the following output − ktm Pulsar Strategy Pattern The strategy pattern recommends an approach where you encapsulate specific families of algorithms allowing the client class responsible for instantiating a particular algorithm. The class that implements the pattern has no knowledge of the actual implementation. Example Here is a code that demonstrates the use of strategy pattern. We have an interface whose case() method is implemented differently by two different classes. The object of testdata class calls the respective case() methods indirectly through its own process() method. <?php interface example { public function case($str); } class ucase implements example { public function case($str) { return strtoupper($str); } } class lcase implements example { public function case($str) { return strtolower($str); } } class testdata { private $data; public function __construct($input) { $this->data = $input; } public function process(example $type) { return $this->data = $type->case($this->data); } } $str = “hello”; $obj = new testdata($str); echo $obj->process(new ucase) . PHP_EOL; $str = “HELLO”; echo $obj->process(new lcase); ?> It will produce the following output − HELLO Hello MVC Design Pattern MVC, which stands for Model, View and Controller, is a very popular softeware architecture pattern. Most of the PHP networks such as Laravel, Symfony etc. implement the MVC architecture. The separation of the role of each layer in an application is as follows − Model − Refers to the data structure. In this case, the database. View − Refers to the user interface. The HTML and CSS. Controller − The “middleman” doing the processing. Accepts input from the view, and works with the model. Self-explanatory, the PHP scripts and libraries themselves. The View acts as the GUI, the Model acts as the back-end and the Control acts as an adapter. Here, three parts are interconnected with each other. It will pass the data and access the data between each other. Example Let us implement the MVC design pattern in pure PHP, JavaScript and HTML in the example below − The presentation layer of the application is view.php, which renders a HTML form. The user submits the data to a controller script. The result returned by the controller is rendered on the web page with a bit of JavaScript view.php <!DOCTYPE html> <html> <head> <title>View (User Interface)</title> <link rel=”stylesheet” href=”style.css”> </head> <body> <form id=”mysearch” action=”controller.php” method=”POST”> <input type=”text” id = “nm” name=”search” required> <input type=”submit” value=”Search”> </form> <div id=”results”></div> <script> let results = document.getElementById(“results”); results.innerHTML = “”; </script> <?php session_start(); if (isset($_SESSION[”result”])) { $arr=$_SESSION[”result”]; foreach ($arr as $obj) {?> <script> results.innerHTML += “<div><?php echo $obj[”id”] . “-” . $obj[”name”] . “</div>”; ?>”; </script> <?php } } ?> </body> </html> The controller script requires model.php, and uses the database object, calls the select method to fetch data from the database. The result is stored in the current session so that it can be accessed on the view page. controller.php <?php session_start(); require “model.php”; $results = $_DB->select( “SELECT * FROM `users` WHERE `name` LIKE ?”, [“%{$_POST[“search”]}%”] ); $_SESSION[”search”] = $_POST[”search”]; $_SESSION[”result”] = $results; Header(“Location: view.php”, true); ?> The model layer of the application is coded in “model.php”. It establishes connection with mysql database named mydb, using PDO extension. model.php <?php class DB { public $error = “”; private $pdo = null; private $stmt = null; var $dsn=”localhost”; var $dbName=”myDB”;
PHP – Regular Expression
PHP – Regular Expressions ”; Previous Next Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality. Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks. PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort. POSIX Regular Expressions PERL Style Regular Expressions POSIX Regular Expressions The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions. The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag. Lets give explanation for few concepts being used in POSIX regular expression. After that we will introduce you with regular expression related functions. Brackets Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters. Sr.No Expression & Description 1 [0-9] It matches any decimal digit from 0 through 9. 2 [a-z] It matches any character from lower-case a through lowercase z. 3 [A-Z] It matches any character from uppercase A through uppercase Z. 4 [a-Z] It matches any character from lowercase a through uppercase Z. The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v. Quantifiers The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence. Sr.No Expression & Description 1 p+ It matches any string containing at least one p. 2 p* It matches any string containing zero or more p”s. 3 p? It matches any string containing zero or one p”s. 4 p{N} It matches any string containing a sequence of N p”s 5 p{2,3} It matches any string containing a sequence of two or three p”s. 6 p{2, } It matches any string containing a sequence of at least two p”s. 7 p$ It matches any string with p at the end of it. 8 ^p It matches any string with p at the beginning of it. Examples Following examples will clear your concepts about matching characters. Sr.No Expression & Description 1 [^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z. 2 p.p It matches any string containing p, followed by any character, in turn followed by another p. 3 ^.{2}$ It matches any string containing exactly two characters. 4 <b>(.*)</b> It matches any string enclosed within <b> and </b>. 5 p(hp)* It matches any string containing a p followed by zero or more instances of the sequence php. Predefined Character Ranges For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set − Sr.No Expression & Description 1 [[:alpha:]] It matches any string containing alphabetic characters aA through zZ. 2 [[:digit:]] It matches any string containing numerical digits 0 through 9. 3 [[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9. 4 [[:space:]] It matches any string containing a space. PHP”s Regexp POSIX Functions PHP currently offers seven functions for searching strings using POSIX-style regular expressions − Sr.No Function & Description 1 ereg() The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise. 2 ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. 3 eregi() The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. 4 eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive. 5 split() The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string. 6 spliti() The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive. 7 sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters. PERL Style Regular Expressions Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section. Lets give explanation for few concepts being used in PERL regular expressions. After that we will introduce you wih regular expression related functions. Meta characters A meta character is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning. For instance, you can search for large money sums using the ”d” meta character: /([d]+)000/, Here d will search for any string of numerical character. Following is the list of meta characters which can be used in PERL Style Regular Expressions. Character Description . a single character s a whitespace character (space, tab, newline) S non-whitespace character d a digit (0-9) D a non-digit w a word character (a-z, A-Z, 0-9, _) W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified Modifiers Several modifiers are available that can make your work with regexps much easier, like