top of page

PHP


PHP-logo.svg
Paradigm    Imperative, functional, object-oriented, procedural, reflective
Designed by    Rasmus Lerdorf
Developer    Zend Technologies
First appeared    1995; 23 years ago[1]
Stable release    
7.2.9[2] / August 16, 2018; 25 days ago
Preview release    
7.3.0 beta 3[3] / August 30, 2018; 11 days ago
Typing discipline    
Dynamic, weak

since version 7.0:

Gradual[4]
Implementation language    C (primarily; some components C++)
OS    Unix-like, Windows
License    PHP License (most of Zend engine under Zend Engine License)
Filename extensions    .php, .phtml, .php3, .php4, .php5, .php7, .phps, .php-s, .pht
Website    secure.php.net
Major implementations
Zend Engine, HHVM, Phalanger, Quercus, Parrot
Influenced by
Perl, C, C++, Java, Tcl[1]
Influenced
Falcon, Hack
 PHP Programming at Wikibooks
PHP: Hypertext Preprocessor (or simply PHP) is a server-side scripting language designed for Web development, but also used as a general-purpose programming language. It was originally created by Rasmus Lerdorf in 1994,[5] the PHP reference implementation is now produced by The PHP Group.[6] PHP originally stood for Personal Home Page,[5] but it now stands for the recursive acronym PHP: Hypertext Preprocessor.[7]

PHP code may be embedded into HTML code, or it can be used in combination with various web template systems, web content management systems, and web frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the web server or as a Common Gateway Interface (CGI) executable. The web server combines the results of the interpreted and executed PHP code, which may be any type of data, including images, with the generated web page. PHP code may also be executed with a command-line interface (CLI) and can be used to implement standalone graphical applications.[8]

The standard PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on almost every operating system and platform, free of charge.[9]

The PHP language evolved without a written formal specification or standard until 2014, with the original implementation acting as the de facto standard which other implementations aimed to follow. Since 2014 work has gone on to create a formal PHP specification.[10]

During the 2010s there have been increased efforts towards standardisation and code sharing in PHP applications by projects such as PHP-FIG in the form of PSR initiatives as well as the Composer dependency manager and associated Packagist repository. PHP hosts a diverse array of web frameworks requiring framework-specific knowledge, with Laravel recently emerging as a popular option by incorporating ideas made popular from other competing non-PHP web frameworks, like Ruby on Rails.


Syntax
Main article: PHP syntax and semantics
The following "Hello, World!" program is written in PHP code embedded in an HTML document:

<!DOCTYPE html>
<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?>
 </body>
</html>
However, as no requirement exists for PHP code to be embedded in HTML, the simplest version of Hello, World! may be written like this, with the closing tag omitted as preferred in files containing pure PHP code[100]

 <?='Hello world';
The PHP interpreter only executes PHP code within its delimiters. Anything outside its delimiters is not processed by PHP, although non-PHP text is still subject to control structures described in PHP code. The most common delimiters are <?php to open and ?> to close PHP sections. The shortened form <? also exists. This short delimiter makes script files less portable, since support for them can be disabled in the local PHP configuration and it is therefore discouraged.[101][102] However, there is no recommendation against the use of the echo short tag <?=.[103] Prior to PHP 5.4.0, this short syntax for echo() only works with the short_open_tag configuration setting enabled, while for PHP 5.4.0 and later it is always available.[104][105][101] The purpose of all these delimiters is to separate PHP code from non-PHP content, such as JavaScript code or HTML markup.[106]

The first form of delimiters, <?php and ?>, in XHTML and other XML documents, creates correctly formed XML processing instructions.[107] This means that the resulting mixture of PHP code and other markup in the server-side file is itself well-formed XML.

Variables are prefixed with a dollar symbol, and a type does not need to be specified in advance. PHP 5 introduced type hinting that allows functions to force their parameters to be objects of a specific class, arrays, interfaces or callback functions. However, before PHP 7.0, type hints could not be used with scalar types such as integer or string.[61]

Unlike function and class names, variable names are case sensitive. Both double-quoted ("") and heredoc strings provide the ability to interpolate a variable's value into the string.[108] PHP treats newlines as whitespace in the manner of a free-form language, and statements are terminated by a semicolon.[109] PHP has three types of comment syntax: /* */ marks block and inline comments; // or # are used for one-line comments.[110] The echo statement is one of several facilities PHP provides to output text, e.g., to a web browser.

In terms of keywords and language syntax, PHP is similar to the C style syntax. if conditions, for and while loops, and function returns are similar in syntax to languages such as C, C++, C#, Java and Perl.

Data types
PHP stores integers in a platform-dependent range, either a 64-bit or 32-bit signed integer equivalent to the C-language long type. Unsigned integers are converted to signed values in certain situations; this behavior is different from other programming languages.[111] Integer variables can be assigned using decimal (positive and negative), octal, hexadecimal, and binary notations.

Floating point numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.[112] PHP has a native Boolean type that is similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl and C++.[112]

The null data type represents a variable that has no value; NULL is the only allowed value for this data type.[112]

Variables of the "resource" type represent references to resources from external sources. These are typically created by functions from a particular extension, and can only be processed by functions from the same extension; examples include file, image, and database resources.[112]

Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled.[112] PHP also supports strings, which can be used with single quotes, double quotes, nowdoc or heredoc syntax.[113]

The Standard PHP Library (SPL) attempts to solve standard problems and implements efficient data access interfaces and classes.[114]

Functions
PHP defines a large array of functions in the core language and many are also available in various extensions; these functions are well documented in the online PHP documentation.[115] However, the built-in library has a wide variety of naming conventions and associated inconsistencies, as described under history above.

Custom functions may be defined by the developer, e.g.:

function myAge(Int $birthYear) : String 
{ // defines a function, this one is named "myAge"
 $yearsOld = date('Y') - $birthYear; // calculates the age
 return $yearsOld . ' year' . ($yearsOld != 1 ? 's' : ''); // returns the age in a descriptive form
}

echo 'I am currently ' . myAge(1995) . ' old.'; // outputs the text concatenated
 // with the return value of myAge()
// As the result of this syntax, myAge() is called.
In 2018, the output of the above sample program is 'I am currently 23 years old.'

In lieu of function pointers, functions in PHP can be referenced by a string containing their name. In this manner, normal PHP functions can be used, for example, as callbacks or within function tables.[116] User-defined functions may be created at any time without being prototyped.[115][116] Functions may be defined inside code blocks, permitting a run-time decision as to whether or not a function should be defined. There is a function_exists function that determines whether a function with a given name has already been defined. Function calls must use parentheses, with the exception of zero-argument class constructor functions called with the PHP operator new, in which case parentheses are optional.

Until PHP 5.3, support for anonymous functions and closures did not exist in PHP. While create_function() exists since PHP 4.0.1, it is merely a thin wrapper around eval() that allows normal PHP functions to be created during program execution.[117] PHP 5.3 added syntax to define an anonymous function or "closure"[118] which can capture variables from the surrounding scope:

function getAdder($x) {
 return function($y) use ($x) {
 return $x + $y;
 };
}

$adder = getAdder(8);
echo $adder(2); // prints "10"
In the example above, getAdder() function creates a closure using passed argument $x (the keyword use imports a variable from the lexical context), which takes an additional argument $y, and returns the created closure to the caller. Such a function is a first-class object, meaning that it can be stored in a variable, passed as a parameter to other functions, etc.[119]

Unusually for a dynamically typed language, PHP supports type declarations on function parameters, which are enforced at runtime. This has been supported for classes and interfaces since PHP 5.0, for arrays since PHP 5.1, for "callables" since PHP 5.4, and scalar (integer, float, string and boolean) types since PHP 7.0.[61] PHP 7.0 also has type declarations for function return types, expressed by placing the type name after the list of parameters, preceded by a colon.[60] For example, the getAdder function from the earlier example could be annotated with types like so in PHP 7:

function getAdder(int $x): \Closure {
 return function(int $y) use ($x) : int {
 return $x + $y;
 };
}

$adder = getAdder(8);
echo $adder(2); // prints "10"
echo $adder(null); // throws an exception because an incorrect type was passed
$adder = getAdder([]); // would also throw an exception
By default, scalar type declarations follow weak typing principles. So, for example, if a parameter's type is int, PHP would allow not only integers, but also convertible numeric strings, floats or booleans to be passed to that function, and would convert them.[61] However, PHP 7 has a "strict typing" mode which, when used, disallows such conversions for function calls and returns within a file.[61]

PHP Objects
Basic object-oriented programming functionality was added in PHP 3 and improved in PHP 4.[6] This allowed for PHP to gain further abstraction, making creative tasks easier for programmers using the language. Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance.[120] In previous versions of PHP, objects were handled like value types.[120] The drawback of this method was that code had to make heavy use of PHP's "reference" variables if it wanted to modify an object it was passed rather than creating a copy of it. In the new approach, objects are referenced by handle, and not by value.

PHP 5 introduced private and protected member variables and methods, along with abstract classes, final classes, abstract methods, and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore, PHP 5 added interfaces and allowed for multiple interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or IteratorAggregate can be used with the foreach language construct. There is no virtual table feature in the engine, so static variables are bound with a name instead of a reference at compile time.[121]

If the developer creates a copy of an object using the reserved word clone, the Zend engine will check whether a __clone() method has been defined. If not, it will call a default __clone() which will copy the object's properties. If a __clone() method is defined, then it will be responsible for setting the necessary properties in the created object. For convenience, the engine will supply a function that imports the properties of the source object, so the programmer can start with a by-value replica of the source object and only override properties that need to be changed.[122]

The following is a basic example of object-oriented programming in PHP:

class Person
{
   public $firstName;
   public $lastName;

   public function __construct($firstName, $lastName = '') { // optional second argument
     $this->firstName = $firstName;
     $this->lastName = $lastName;
   }

   public function greet() {
     return 'Hello, my name is ' . $this->firstName .
       (($this->lastName != '') ? (' ' . $this->lastName) : '') . '.';
   }

   public static function staticGreet($firstName, $lastName) {
     return 'Hello, my name is ' . $firstName . ' ' . $lastName . '.';
   }
}

$he = new Person('John', 'Smith');
$she = new Person('Sally', 'Davis');
$other = new Person('iAmine');

echo $he->greet(); // prints "Hello, my name is John Smith."
echo '<br />';

echo $she->greet(); // prints "Hello, my name is Sally Davis."
echo '<br />';

echo $other->greet(); // prints "Hello, my name is iAmine."
echo '<br />';

echo Person::staticGreet('Jane', 'Doe'); // prints "Hello, my name is Jane Doe."
The visibility of PHP properties and methods is defined using the keywords public, private, and protected. The default is public, if only var is used; var is a synonym for public. Items declared public can be accessed everywhere. protected limits access to inherited classes (and to the class that defines the item). private limits visibility only to the class that defines the item.[123] Objects of the same type have access to each other's private and protected members even though they are not the same instance.

Implementations
The original, only complete and most widely used PHP implementation is powered by the Zend Engine and known simply as PHP. To disambiguate it from other implementations, it is sometimes unofficially called "Zend PHP". The Zend Engine compiles PHP source code on-the-fly into an internal format that it can execute, thus it works as an interpreter.[124][125] It is also the "reference implementation" of PHP, as PHP has no formal specification, and so the semantics of Zend PHP define the semantics of PHP. Due to the complex and nuanced semantics of PHP, defined by how Zend works, it is difficult for competing implementations to offer complete compatibility.

PHP's single-request-per-script-execution model, and the fact the Zend Engine is an interpreter, leads to inefficiency; as a result, various products have been developed to help improve PHP performance. In order to speed up execution time and not have to compile the PHP source code every time the web page is accessed, PHP scripts can also be deployed in the PHP engine's internal format by using an opcode cache, which works by caching the compiled form of a PHP script (opcodes) in shared memory to avoid the overhead of parsing and compiling the code every time the script runs. An opcode cache, Zend Opcache, is built into PHP since version 5.5.[126] Another example of a widely used opcode cache is the Alternative PHP Cache (APC), which is available as a PECL extension.[127]

While Zend PHP is still the most popular implementation, several other implementations have been developed. Some of these are compilers or support JIT compilation, and hence offer performance benefits over Zend PHP at the expense of lacking full PHP compatibility. Alternative implementations include the following:

HHVM (HipHop Virtual Machine) – developed at Facebook and available as open source, it converts PHP code into a high-level bytecode (commonly known as an intermediate language), which is then translated into x86-64 machine code dynamically at runtime by a just-in-time (JIT) compiler, resulting in up to 6× performance improvements.[128]
Parrot – a virtual machine designed to run dynamic languages efficiently; Pipp transforms the PHP source code into the Parrot intermediate representation, which is then translated into the Parrot's bytecode and executed by the virtual machine.
Phalanger – compiles PHP into Common Intermediate Language (CIL) bytecode
Quercus – compiles PHP into Java bytecode
HipHop – developed at Facebook and available as open source, it transforms the PHP scripts into C++ code and then compiles the resulting code, reducing the server load up to 50%. In early 2013, Facebook deprecated it in favor of HHVM due to multiple reasons, including deployment difficulties and lack of support for the whole PHP language, including the create_function() and eval() constructs.[129]
Licensing
PHP is free software released under the PHP License, which stipulates that:[130]

Products derived from this software may not be called "PHP", nor may "PHP" appear in their name, without prior written permission from group@php.net. You may indicate that your software works in conjunction with PHP by saying "Foo for PHP" instead of calling it "PHP Foo" or "phpfoo".

This restriction on use of "PHP" makes the PHP License incompatible with the General Public License (GPL), while the Zend License is incompatible due to an advertising clause similar to that of the original BSD license.[131]

Development and community
PHP includes various free and open-source libraries in its source distribution, or uses them in resulting PHP binary builds. PHP is fundamentally an Internet-aware system with built-in modules for accessing File Transfer Protocol (FTP) servers and many database servers, including PostgreSQL, MySQL, Microsoft SQL Server and SQLite (which is an embedded database), LDAP servers, and others. Numerous functions familiar to C programmers, such as those in the stdio family, are available in standard PHP builds.[132]

PHP allows developers to write extensions in C to add functionality to the PHP language. PHP extensions can be compiled statically into PHP or loaded dynamically at runtime. Numerous extensions have been written to add support for the Windows API, process management on Unix-like operating systems, multibyte strings (Unicode), cURL, and several popular compression formats. Other PHP features made available through extensions include integration with IRC, dynamic generation of images and Adobe Flash content, PHP Data Objects (PDO) as an abstraction layer used for accessing databases,[133][134][135][136][137][138][139] and even speech synthesis. Some of the language's core functions, such as those dealing with strings and arrays, are also implemented as extensions.[140] The PHP Extension Community Library (PECL) project is a repository for extensions to the PHP language.[141]

Some other projects, such as Zephir, provide the ability for PHP extensions to be created in a high-level language and compiled into native PHP extensions. Such an approach, instead of writing PHP extensions directly in C, simplifies the development of extensions and reduces the time required for programming and testing.[142]

The PHP Group consists of ten people (as of 2015): Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski.[143]

Zend Technologies provides a PHP Certification based on PHP 5.5[144] exam for programmers to become certified PHP developers.

Installation and configuration
There are two primary ways for adding support for PHP to a web server – as a native web server module, or as a CGI executable. PHP has a direct module interface called Server Application Programming Interface (SAPI), which is supported by many web servers including Apache HTTP Server, Microsoft IIS, Netscape (now defunct) and iPlanet. Some other web servers, such as OmniHTTPd, support the Internet Server Application Programming Interface (ISAPI), which is a Microsoft's web server module interface. If PHP has no module support for a web server, it can always be used as a Common Gateway Interface (CGI) or FastCGI processor; in that case, the web server is configured to use PHP's CGI executable to process all requests to PHP files.[145]

PHP-FPM (FastCGI Process Manager) is an alternative FastCGI implementation for PHP, bundled with the official PHP distribution since version 5.3.3.[146] When compared to the older FastCGI implementation, it contains some additional features, mostly useful for heavily loaded web servers.[147]

When using PHP for command-line scripting, a PHP command-line interface (CLI) executable is needed. PHP supports a CLI SAPI as of PHP 4.3.0.[148] The main focus of this SAPI is developing shell applications using PHP. There are quite a few differences between the CLI SAPI and other SAPIs, although they do share many of the same behaviors.[149]

PHP has a direct module interface called SAPI for different web servers;[150] in case of PHP 5 and Apache 2.0 on Windows, it is provided in form of a DLL file called php5apache2.dll,[151] which is a module that, among other functions, provides an interface between PHP and the web server, implemented in a form that the server understands. This form is what is known as a SAPI.

There are different kinds of SAPIs for various web server extensions. For example, in addition to those listed above, other SAPIs for the PHP language include the Common Gateway Interface (CGI) and command-line interface (CLI).[150][152]

PHP can also be used for writing desktop graphical user interface (GUI) applications, by using the PHP-GTK extension. PHP-GTK is not included in the official PHP distribution,[145] and as an extension it can be used only with PHP versions 5.1.0 and newer. The most common way of installing PHP-GTK is compiling it from the source code.[153]

When PHP is installed and used in cloud environments, software development kits (SDKs) are provided for using cloud-specific features. For example:

Amazon Web Services provides the AWS SDK for PHP[154]
Windows Azure can be used with the Windows Azure SDK for PHP.[155]
Numerous configuration options are supported, affecting both core PHP features and extensions.[156][157] Configuration file php.ini is searched for in different locations, depending on the way PHP is used.[158] The configuration file is split into various sections,[159] while some of the configuration options can be also set within the web server configuration.[160]

Use

A broad overview of the LAMP software bundle, displayed here together with Squid.
PHP is a general-purpose scripting language that is especially suited to server-side web development, in which case PHP generally runs on a web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create dynamic web page content or dynamic images used on websites or elsewhere.[161] It can also be used for command-line scripting and client-side graphical user interface (GUI) applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems (RDBMS). Most web hosting providers support PHP for use by their clients. It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use.[9]


Dynamic web page: example of server-side scripting (PHP and MySQL).
PHP acts primarily as a filter,[162] taking input from a file or stream containing text and/or PHP instructions and outputting another stream of data. Most commonly the output will be HTML, although it could be JSON, XML or binary data such as image or audio formats. Since PHP 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine, giving improved performance over its interpreter predecessor.[163]

Originally designed to create dynamic web pages, PHP now focuses mainly on server-side scripting,[164] and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's ASP.NET, Sun Microsystems' JavaServer Pages,[165] and mod_perl. PHP has also attracted the development of many software frameworks that provide building blocks and a design structure to promote rapid application development (RAD). Some of these include PRADO, CakePHP, Symfony, CodeIgniter, Laravel, Yii Framework, Phalcon and Zend Framework, offering features similar to other web frameworks.

The LAMP architecture has become popular in the web industry as a way of deploying web applications.[166] PHP is commonly used as the P in this bundle alongside Linux, Apache and MySQL, although the P may also refer to Python, Perl, or some mix of the three. Similar packages, WAMP and MAMP, are also available for Windows and OS X, with the first letter standing for the respective operating system. Although both PHP and Apache are provided as part of the Mac OS X base install, users of these packages seek a simpler installation mechanism that can be more easily kept up to date.

As of April 2007, over 20 million Internet domains had web services hosted on servers with PHP installed and mod_php was recorded as the most popular Apache HTTP Server module.[167] As of June 2018, PHP was used as the server-side programming language on 83.5% of websites where the language could be determined.[168] Web content management systems written in PHP include MediaWiki,[169] Joomla,[170] eZ Publish, eZ Platform, SilverStripe,[171] WordPress,[172] Drupal,[173] and Moodle.[174] Websites written in PHP, in back-end and/or user-facing portion, include Facebook,[175] Digg,[176] Tumblr,[177] Dailymotion,[178] and Slack.[179]

For specific and more advanced usage scenarios, PHP offers a well defined and documented way for writing custom extensions in C or C++.[180][181][182][183][184][185][186] Besides extending the language itself in form of additional libraries, extensions are providing a way for improving execution speed where it is critical and there is room for improvements by using a true compiled language.[187][188] PHP also offers well defined ways for embedding itself into other software projects. That way PHP can be easily used as an internal scripting language for another project, also providing tight interfacing with the project's specific internal data structures.[189]

PHP received mixed reviews due to lacking support for multithreading at the core language level,[190] though using threads is made possible by the "pthreads" PECL extension.[191][192]

As of January 2013, PHP was used in more than 240 million websites (39% of those sampled) and was installed on 2.1 million web servers.[193]

A command line interface, php-cli, and two ActiveX Windows Script Host scripting engines for PHP have been produced.

Security
In 2017, 3% of all vulnerabilities listed by the National Vulnerability Database were linked to PHP;[194] historically, about 30% of all vulnerabilities listed since 1996 in this database are linked to PHP. Technical security flaws of the language itself or of its core libraries are not frequent (22 in 2009, about 1% of the total although PHP applies to about 20% of programs listed).[195] Recognizing that programmers make mistakes, some languages include taint checking to automatically detect the lack of input validation which induces many issues. Such a feature is being developed for PHP,[196] but its inclusion into a release has been rejected several times in the past.[197][198]

There are advanced protection patches such as Suhosin and Hardening-Patch, especially designed for web hosting environments.[199]

Historically, old versions of PHP had some configuration parameters and default values for such runtime settings that made some PHP applications prone to security issues. Among these, magic_quotes_gpc and register_globals[200] configuration directives were the best known; the latter made any URL parameters become PHP variables, opening a path for serious security vulnerabilities by allowing an attacker to set the value of any uninitialized global variable and interfere with the execution of a PHP script. Support for "magic quotes" and "register globals" settings has been deprecated as of PHP 5.3.0, and removed as of PHP 5.4.0.[201]

Another example for the potential runtime settings vulnerability comes from failing to disable PHP execution (e.g. via engine configuration directive)[202] for the directory where uploaded files are stored; enabling it can result in execution of malicious PHP code embedded within the uploaded files, e.g. when allowing users to upload images.[203][204][205] The best practice is to either locate the image directory outside of the document root available to the web server and serve it via intermediary script, or disable PHP execution for the directory which stores the uploaded files.

Also, enabling the dynamic loading of PHP extensions (via enable_dl configuration directive)[206] in a shared web hosting environment can lead to security issues.[207][208]

Implied type conversions that result in different values being treated as equal, sometimes against the programmer's intent, can lead to security issues. For example, the result of the comparison 0e1234 == 0 is true, because the first compared value is treated as scientific notation having the value (0×101234), i.e. zero. Errors like this resulted in authentication vulnerabilities in Simple Machines Forum,[209] Typo3[210] and phpBB[211] when MD5 password hashes were compared. The recommended way is to use hash_equals() (for timing attack safety), strcmp or the identity operator (===), as 0e1234 === 0 results in false.[212]

In a 2013 analysis of over 170,000 website defacements, published by Zone-H, the most frequently (53%) used technique was exploitation of file inclusion vulnerability, mostly related to insecure usage of the PHP functions include, require, and allow_url_fopen.[213][214]

bottom of page