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 −
passphraseThe passphrase. If the passphrase is shorter than expected, padded with NULL characters; if the passphrase is longer than expected, it is truncated.
4
optionsoptions is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
5
ivA non-NULL Initialization Vector.
6
tagThe authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).
7
aadAdditional authenticated data.
8
tag_lengthThe length of the authentication tag. Its value can be between 4 and 16 for GCM mode.
The function returns the encrypted string on success or false on failure.
The openssl_decrypt() Function
This function takes a raw or base64 encoded string and decrypts it using a given method and key.
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.
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) −
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
PHPs two data types resource and NULL are classified as special types. An object of resource type refers to external resources like database connection, file streams etc. On the other hand, a NULL data type is a variable without any data assigned to it. In this chapter, we shall learn more about these types.
Resource Type
A PHP program often needs to interact with an external environment such as a database, or a disk file etc. These are treated as resources in PHP. Resource is a special data type that refers to any such external resource. PHP uses relevant functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable.
PHP’s Zend engine uses reference counting system. Hence, a resource with zero reference count is destroyed automatically by garbage collector and the memory used by resource data type need not be freed manually.
Different built-in PHP functions return respective resource variables. Subsequently, PHP uses them for interacting with the corresponding external environment. For example, the fopen() function returns a file resource, which acts as a file handle and the read/write operations on the file are facilitated by this resource variable.
The following table summarizes different functions that return resource variables −
Resource Type
Built-in functions
Definition
Produced
Sold
bzip2
bzopen()
bzclose()
Bzip2 file
curl
curl_init()
curl_close()
Curl session
ftp
ftp_connect(),
ftp_close()
FTP stream
mssql link
mssql_connect()
mssql_close()
Link to Microsoft SQL Server database
mysql link
mysql_connect()
mysql_close()
Link to MySQL database
mysql result
mysql_db_query(),
mysql_free_result()
MySQL result
oci8 connection
oci_connect()
oci_close()
Connection to Oracle Database
ODBC link
odbc_connect()
odbc_close()
Link to ODBC database
pdf document
pdf_new()
pdf_close()
PDF document
stream
opendir()
closedir()
Dir handle
stream
fopen(), tmpfile()
fclose()
File handle
socket
socket_create()
Socket_close()
Socket handle
xml
xml_parser_create()
xml_parser_free()
XML parser
zlib
gzopen()
gzclose()
gz-compressed file
zlib.deflate
deflate_init()
None()
incremental deflate context
zlib.inflate
inflate_init()
None()
incremental inflate context
PHP has get_resource_type() function that returns resource type of a variable.
get_resource_type(resource$handle):string
where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type.
There is also get_resource_id() function an integer identifier for the given resource.
get_resource_id(resource$resource):int
Example
This function provides a type-safe way for generating the integer identifier for a given resource.
<?php
$fp = fopen("hello.php", "r");
$resource = get_resource_type($fp);
$id = get_resource_id($fp);
echo "The resource type is : $resource The resource ID is : $id";
?>
It will produce the following output −
The resource type is : stream The resource ID is : 5
NULL type
In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function.
$var=NULL;
It is possible to cast variable of other type to null, although casting null to other type has been deprecated from PHP 7.2. In earlier versions, casting was done using (unset)$var syntax
Example
The following example shows how to assign NULL to a variable
<?php
$var=NULL;
var_dump($var);
?>
It will produce the following output −
NULL
Example
The following example performs null variable to other primary variables −
Prior to version 7, PHP parser used to report errors in response to various conditions. Each error used to be of a certain predefined type. PHP7 has changed the mechanism of error reporting. Instead of traditional error reporting, most errors are now reported by throwing error exceptions.
The exception handling mechanism in PHP is similar to many other languages, and is implemented with the try, catch, throw and finally keywords.
The Throwable Interface
Exceptions in PHP implements the Throwable interface. The Throwable interface acts as the base for any object that can be thrown via throw statement, including Error and Exception objects.
A user defined class cannot implement Throwable interface directly. Instead, to declare a user defined exception class, it must extend the Exception class.
PHP code with potential exceptions is surrounded in a try block. An exception object is thrown if it is found, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block. Moreover, there may be more than one catch/finally blocks corresponding to a try block.
try{// throw errors in the try-block // if an error occurs we can throw an exceptionthrownewException('this is an error.');}catch(Exception$e){// catch the throws in the catch-block // do something with the exception object, eg. // display its messageecho'Error message: '.$e->getMessage();}
If an exception is thrown and there is no catch block, the exception will “bubble up” until it finds a matching catch block. If the call stack is unwound all the way to the global scope without encountering a matching catch block, a global exception handler will be called (if it is set) otherwise the program will terminate with a fatal error.
set_exception_handler
This function sets the default exception handler if an exception is not caught within a try/catch block. After the callback is executed, the program execution will stop.
The $callback parameter is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.
The function returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.
Example
Take a look at the following example −
<?php
function handler($ex) {
echo "Uncaught exception is : " , $ex->getMessage(), "\n";
}
set_exception_handler('handler');
throw new Exception('Not Found Exception');
echo "not included Executed\n";
?>
It will produce the following output −
Uncaught exception is : Not Found Exception
SPL Exceptions
Standard PHP library contains predefined exceptions −
Sr.No
Predefined Exceptions
1
LogicExceptionException that represents error in the program logic.
2
BadFunctionCallExceptionException thrown if a callback refers to an undefined function or if some arguments are missing.
3
BadMethodCallExceptionException thrown if a callback refers to an undefined method or if some arguments are missing.
4
DomainExceptionException thrown if a value does not adhere to a defined valid data domain.
5
InvalidArgumentExceptionException thrown if an argument is not of the expected type.
6
LengthExceptionException thrown if a length is invalid.
7
OutOfRangeExceptionException thrown when an illegal index was requested.
8
RuntimeExceptionException thrown if an error which can only be found on runtime occurs.
9
OutOfBoundsExceptionException thrown if a value is not a valid key.
10
OverflowExceptionException thrown when adding an element to a full container.
11
RangeExceptionException thrown to indicate range errors during program execution. An arithmetic error other than under/overflow.
12
UnderflowExceptionException thrown when performing an invalid operation on an empty container, such as removing an element.
13
UnexpectedValueExceptionException thrown if a value does not match with a set of values.
User-defined Exception
You can define a custom exception class that extends the base Exception class. Following script defines a custom exception class called myException. This type of exception is thrown if value of $num is less than 0 or greater than 100.
Example
The getMessage() method of Exception class returns the error message and getLine() method returns line of code in which exception appears.
<?php
class myException extends Exception {
function message() {
return "error : ". $this->getMessage(). "in line no". $this->getLine();
}
}
$num=125;
try {
if ($num>100 || $num<0)
throw new myException("$num is invalid number");
else
echo "$num is a valid number";
}
catch (myException $m) {
echo $m->message();
}
?>
Run the above code with $num=125 and $num=90 to get an error message and a message of valid number −
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.
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_NONENo error has occurred
2
JSON_ERROR_DEPTHThe maximum stack depth has been exceeded
3
JSON_ERROR_STATE_MISMATCHInvalid or malformed JSON
4
JSON_ERROR_CTRL_CHARControl character error, possibly incorrectly encoded
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_LOWStrips characters that have a numerical value <32.
2
FILTER_FLAG_STRIP_HIGHStrips characters that have a numerical value >127.
FILTER_FLAG_ALLOW_FRACTIONAllows a period (.) as a fractional separator in numbers.
5
FILTER_FLAG_ALLOW_THOUSANDAllows a comma (,) as a thousands separator in numbers.
6
FILTER_FLAG_ALLOW_SCIENTIFICAllows an e or E for scientific notation in numbers.
7
FILTER_FLAG_NO_ENCODE_QUOTESIf this flag is present, single (‘) and double (“) quotes will not be encoded.
8
FILTER_FLAG_ENCODE_LOWEncodes all characters with a numerical value <32.
9
FILTER_FLAG_ENCODE_HIGHEncodes all characters with a numerical value >127.
10
FILTER_FLAG_ENCODE_AMPEncodes ampersands (&).
11
FILTER_NULL_ON_FAILUREReturns null for unrecognized values.
12
FILTER_FLAG_ALLOW_OCTALRegards inputs starting with a zero (0) as octal numbers.
13
FILTER_FLAG_ALLOW_HEXRegards inputs starting with 0x or 0X as hexadecimal numbers.
14
FILTER_FLAG_EMAIL_UNICODEAllows the local part of the email address to contain Unicode characters.
15
FILTER_FLAG_IPV4Allows the IP address to be in IPv4 format.
16
FILTER_FLAG_IPV6Allows the IP address to be in IPv6 format.
17
FILTER_FLAG_NO_PRIV_RANGEFails 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_RANGEFails 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_RANGEFails validation for non global IPv4/IPv6 ranges
20
FILTER_FLAG_SCHEME_REQUIREDRequires the URL to contain a scheme part.
21
FILTER_FLAG_HOST_REQUIREDRequires the URL to contain a host part.
22
FILTER_FLAG_PATH_REQUIREDRequires the URL to contain a path part.
23
FILTER_FLAG_QUERY_REQUIREDRequires the URL to contain a query string.
24
FILTER_REQUIRE_SCALARRequires the value to be scalar.
25
FILTER_REQUIRE_ARRAYRequires the value to be an array.
26
FILTER_FORCE_ARRAYIf 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.
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.
The type parameter is one of the constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. Second parameter is var_name, the name of a variable to get. You can use the filter to be applied. Use any of the predefined filter flags. If omitted, FILTER_DEFAULT will be used
The function returns the value of the requested variable on success, false if the filter fails, or null if the var_name variable is not set.
Example
Take a look at the following example −
<?php
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
This function is useful for retrieving many values without repetitively calling filter_input().
The type parameter is one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
The options parameter is an array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.
The function returns an array containing the values of the requested variables on success. If the input array designated by type is not populated, the function returns null if the FILTER_NULL_ON_FAILURE flag is not given, or false otherwise. For other failures, false is returned.
Example
To include an array in the HTTP request, we use the following HTML form in “hello.html”, and send it by POST method.
<!DOCTYPE html><html><body><h1>Filter Input Array</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="age">Enter your age<label><input type = "text" id="age" name="age"></p><input type="submit"></form></body></html>
The PHP script to validate the input array is as follows −
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;
}
}
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 dont 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);
}
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);
}
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
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.
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.
The PHP ecosystem has a number of web frameworks. Some of the popular PHP web frameworks are Laravel, Yii, CakePHP etc. While one can build a web application with the help of core PHP, developers are increasingly preferring web frameworks for rapid application development.
What are Software Frameworks?
In computer programming, a software framework is a collection of libraries and classes that provide a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code for routine but tedious low-level processes.
A framework provides a reusable software environment that quickly builds a minimal working template application. Developer can then modify these blocks for additional functionality.
Each framework is built to help the developer build an application of a certain type. For example, web frameworks (sometimes also called “web application framework”) are used for the development of web applications including web services, web resources, and web APIs.
In this chapter, let us take a brief overview of some of the popular PHP frmeworks.
FuelPHP
FuelPHP (https://fuelphp.com/) works based on Model View Control and having innovative plug ins. FuelPHP supports router-based theory where you might route directly to a nearer the input uri, making the closure the controller and giving it control of further execution.
CakePHP
CakePHP (https://cakephp.org/) is a great source to build up simple and great web application in an easy way. Some great features which are inbuilt in PHP are input validation, SQL injection prevention that keeps you application safe and secure.
FlightPHP
FlightPHP (https://flightphp.com/) is very helpful to make RESTful web services and it is under MIT licence.
Symfony
Symfony is for highly professional developers to build websites with PHP components such as Drupal, PHPBB, laravel, eX, OROCRM and piwik.
yiiFramework
YiiFramework (https://www.yiiframework.com/) works based on web 2.0 with high end security. It included input Validation, output filtering, and SQL injection.
Laravel
Laravel (https://laravel.com/) is most useful for RESRful Routing and light weight bled tempting engine. Laravel has integrated with some of great components of well tested and reliable code.
Zend
Zend (https://framework.zend.com/) is Modern frame work for performing high end web applications. This works based on Cryptographic and secure coding tools. Zend Framework is a collection of professional PHP packages with more than 570 million installations.
It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features.
Codeigniter
Codeigiter is simple to develop small footprint for developer who need simple and elegant tool kit to create innovative web applications.
Phalcon PHP
Pholcon (https://phalcon.io/en-us) is a PHP framework that works based on MVC and integrated with innovative architecture to do perform faster.
PHPixie
PHPixie (https://phpixie.com/) works based on MVC and designed for fast and reliability to develop web sites.
Agavi
Agavi is a powerful and scalable PHP5 application framework and it follows the MVC model. Agavi can help PHP developers in writing clean and maintainable code.
PERL is a dynamically typed, high level and general-purpose programming language. It is normally believed that PERL is an acronym for Practical Extraction and Reporting Language. PHP on the other hand is also a general-purpose scripting language. Initially PHP used to be a short for Personal Home Page, but these days it has now been recognized as a recursive acronym PHP: Hypertext Preprocessor.
In this chapter, certain major similarities and differences in between PHP and PERL are listed. This will help PERL developers to understand PHP very quickly and avoid common mistakes.
Similarities between PERL and PHP
Both Perl and PHP are scripting languages. They are not used to build native standalone executables in advance of execution.
Early versions of PHP were inspired by PERL. PHP’s basic syntax is very similar to PERL. Both share a lot of syntactic features with C. Their code is insensitive to whitespace, Each statement is terminated by semicolons.
Both PHP and PERL use curly braces to organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas, in both the cases.
All variables in PHP look like scalar variables in PERL: a name with a dollar sign ($) in front of it.
Since both the languages are dynamically typed, you dont need to declare the type of a PHP as well as a PERL variable before using it.
In PHP, as in PERL, variables have no intrinsic type other than the value they currently hold. You can store either number or string in same type of variable.
Both PHP and Perl do more interpretation of double-quoted strings (“string”) than of single-quoted strings (‘string’).
Differences between PERL and PHP
PHP can be embedded inside HTML. Although it is possible to run a PHP script from the command line, it is more popularly used as a server-side scripting language on a Web server and used for producing Web pages.
If you are used to writing CGI scripts in PERL, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block.
No @ or % variables − PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound. In PERL, the array variable is prefixed with @ symbol. Also, the hash variable is prefixed by % symbol.
Unlike PERL, PHP has a single datatype called an array which can be an indexed array or associative array, which is similar to hash in PERL.
Function calls in PHP look pretty much like subroutine calls in PERL. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the case in PERL.
Scope of variables in PERL is global by default. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default.
No module system in PHP as such. In PHP there is no real distinction between normal code files and code files used as imported libraries.
Break and continue rather than next and last PHP is more like C language and uses break and continue instead of next and last statement as in PERL.
No elsif − A minor spelling difference: Perl’s elsif is PHP’s elseif.
In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */) and Java-style single-line comments (// comment).
Regular expressions − PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its “Perl-compatible” regular expression functions.