PHP
File:PHP-logo.png | |
Developer(s) | The PHP Group |
---|---|
Stable release | |
Repository | |
Operating system | Cross-platform |
Type | Scripting language |
License | PHP License 3.01 |
Website | http://www.php.net/ |
PHP is a scripted programming language that can be used to create websites. Short for "PHP: Hypertext Preprocessor" (the initials actually come from the earliest version of the program, which was called "Personal Home Page Tools"), it is an open-source, reflective programming language used mainly for developing server-side applications and dynamic web content, and more recently, a broader range of software applications.
PHP allows interaction with a large number of relational database management systems, such as MySQL, Oracle, IBM DB2, Microsoft SQL Server, PostgreSQL and SQLite. PHP runs on most major operating systems, including Unix, Linux, Windows, and Mac OS X, and can interact with many major web servers. The official PHP website contains very extensive documentation.
There is a command line interface (CLI), as well as GUI libraries such as the Gimp Tool Kit (GTK+) and text mode libraries like Ncurses and Newt.
PHP is the result of the efforts of many contributors. It is licensed under the PHP License, a BSD-style license. Since version 4, it has been powered by the Zend engine.
History
PHP was originally designed as a small set of Perl scripts, followed by a rewritten set of CGI binaries written in C by the Danish-Canadian programmer Rasmus Lerdorf in 1994 to display his résumé and to collect certain data, such as how much traffic his page was receiving. "Personal Home Page Tools" was publicly released on 8 June 1995 after Lerdorf combined it with his own Form Interpreter to create PHP/FI.
Zeev Suraski and Andi Gutmans, two Israeli developers of the Technion - Israel Institute of Technology, rewrote the parser in 1997 and formed the base of PHP 3, changing the language's name to the recursive acronym "PHP: Hypertext Preprocessor". The development team officially released PHP/FI 2 in November 1997 after months of beta testing. Public testing of PHP 3 began immediately and the official launch came in June 1998. Suraski and Gutmans then started a new rewrite of PHP's core, producing the Zend engine in 1999 (a page at www.zend.com states that PHP 3 was powered by Zend Engine 0.5). They also founded Zend Technologies in Ramat Gan, Israel which has since overseen the PHP advances.
In May 2000, PHP 4, powered by the Zend Engine 1.0, was released.
On July 13, 2004, PHP 5 was released, powered by Zend Engine II. PHP 5 includes new features such as PHP Data Objects (PDO) and more performance enhancements taking advantage of the new engine.
Support for objects
Up until version 3, PHP had no object-oriented features. Basic object functionality was added in version 3. The same semantics were implemented in PHP 4 as well as pass-by-reference and return-by-reference for objects but the implementation still lacked the powerful and useful features of other object-oriented languages like C++ and Java.
In version 5, which was released in July 2004, PHP's object-oriented functionality has been very much enhanced and is more robust and complete.
Usage
The LAMP architecture (short for Linux, Apache, MySQL, PHP) has become popular in the Web industry as a way of deploying inexpensive, reliable, scalable, secure web applications (the 'P' in LAMP can also stand for Perl or Python).
Examples of PHP applications include phpBB and MediaWiki.
The PHP model can be seen as an alternative to Microsoft's ASP.NET/C#/VB.NET system, Macromedia's ColdFusion system, Sun Microsystems' JSP/Java system, the Zope/Python system, the Mod perl/Perl system, and more recently the Ruby on Rails framework.
Syntax
Sample code
Hello world
Here is a Hello World code example (See Basic syntax in the PHP manual):
<?php echo 'Hello World!'; ?>
The (arguably) simplest "Hello World" program in PHP is:
<? echo 'Hello World!'?>
A slightly smaller example:
<?='Hello World!'?>
However, the previous two examples both rely on the short_open_tag configuration option being set to true. Use of the <? short open tag limits the portability of code, as administrators may choose to disable the option.
phpinfo
This simple code snippet displays information about PHP's configuration settings, loaded modules, variables, and more:
<?php phpinfo(); ?>
Data types
Arrays
$myArray = array('key 1' => 'string value 1', 2005, new StdClass());
[1]
Arrays are heterogenous, meaning a single array can contain objects of more than one type. They can be used as ordered lists of only values and as hashes with keys and values, even simultaneously. When used as hashes (also referred to as associative arrays), the ordering of keys is preserved.
Strings
Variables are evaluated inside double quotation marks ("), but not inside single quotation marks ('). Functions and other expressions are not evaluated inside double quotes but can be added to strings using periods for concatenation.
$myString = 'string' . function() . 'rest of string';
[2]
A period (.) concatenates strings together. [3]
Boolean
PHP has a native Boolean type, named "boolean".
Boolean variables have two possible values True and False
$myBoolean = True;
$myBoolean = False;
This type is similar to the native Boolean types in Java and C++. It differs from the approach used by other languages such as Perl and C, where non-zero values are intepreted as true, and zero values interpreted as false. However, this approach can still be used in PHP, using the Boolean type conversion rules. [4]
Integer
The Integer type stores whole numbers in a platform-dependent range. This range is typically that of 32-bit signed integers. Portable code should not assume that values outside this range can be represented in an integer variable. Integer variables can be assigned using decimal (positive and negative), octal and hexadecimal notations.
$decimal = 1234; // decimal number
$negative = -123; // a negative number
$octal = 0123; // octal number (equivalent to 83 decimal)
$hexadecimal = 0x1A; // hexadecimal number (equivalent to 26 decimal)
[5]
Floating Point Numbers
The Floating point type stores Real numbers in a platform-specific range. They can be specified using floating point notation, or two forms of Scientific notation:
$float = 1.234;
$float = 1.2e3;
$float = 1E-23;
Null
The Null data type represents a variable that has no value. The only value in the Null data type is NULL.
$null = NULL;
Resource
Variables of type resource 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.
Objects
Support for object-oriented programming in PHP 5 (from the PHP Manual):
- New Object Model
- PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).
- Private and Protected Members
- PHP 5 introduces private and protected member variables, they allow you to define the visibility of class properties.
- Private and Protected Methods
- Private and protected methods are also introduced.
- Abstract Classes and Methods
- PHP 5 also introduces abstract classes and abstract methods. An abstract method only declares the method's signature and does not provide an implementation. A class that contains abstract methods needs to be declared an abstract class.
- Interfaces
- A class may implement an arbitrary list of interfaces.
- Object Cloning
- If the developer asks to create a copy of an object by using the reserved word clone, the Zend engine will check if a
__clone()
method has been defined or not. If not, it will call a default__clone()
which will copy all of the object's properties. If a__clone()
method is defined, then it will be responsible to set the necessary properties in the created object. For convenience, the engine will supply a function that imports all of the properties from the source object, so that they can start with a by-value replica of the source object, and only override properties that need to be changed. - Unified Constructors
- PHP 5 introduces a standard way of declaring constructor methods by calling them by the name
__construct()
. - Destructors
- PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++: When the last reference to an object is destroyed, the object's destructor (a class method named
__destruct()
that receives no parameters) is called before the object is freed from memory. - Exceptions
- PHP 4 had no exception handling. PHP 5 introduces an exception model similar to that of other programming languages.
More additions and examples of the additions mentioned above are available in the Classes and Objects chapter of the PHP 5 manual.
It should be noted that the static method and class variable features in Zend Engine 2 do not work the way some expect. There is no virtual table feature in the Engine, so the static variables are bound with a name at compile time instead of with a reference. This can lead to unexpected behavior, if you do not understand this.
Here is an example of creating an object in PHP5:
<?php class Car { public $miles; // variable that can be accessed outside the class private $mpg; // variable that can only be accessed within the class protected $mph; // variable that can only be accessed from within the class, and // from any inherited child classes public function __construct($param) { // constructor is called when object "Car" is created $this->miles = $param; } public function start() { // starts the car... } public function stop() { // stops the car... } public function getMpg() { return $this->mpg; } } $car = new Car($param); echo $car->miles; // echos the value of the property "miles" of the class "Car" ?>
Whitespace
PHP treats new lines as whitespace, in the manner of a free-form language (except when inside string quotes). Statements are terminated only by a semicolon (;) except in a few special cases. [10]
Comments
// comment -- is terminated at the first line break
/* multi-line comment */
# comment -- its use is discouraged
Resources
Libraries
PHP includes a large number of free and open-source libraries with the core build. PHP is a fundamentally Internet-aware system with modules built in for accessing FTP servers, many database servers, embedded SQL libraries like embedded MySQL and SQLite, LDAP servers, and others. Many functions familiar to C programmers such as the printf family are available in the standard PHP build.
PHP extensions exist which, among other features, add support for the Windows API, process management on Unix-like operating systems, cURL, and the ZIP/gzip/bzip2/RAR/LZF compression formats. Some of the more unusual features are on-the-fly Macromedia Flash generation, integration with Internet relay chat, and generation of dynamic images (where the content of the image can be changed). Some additional extensions are available via the PHP Extension Community Library (PECL).
This is the present list of all officially documented libraries: [11]
Source code encoders
Encoders offer some protection for intellectual property by hindering source code reverse engineering. PHP scripts are compiled into native byte-code. The downside of this approach is that a special extension has to be installed on the server in order to run encoded scripts.
Some of the commercialy available PHP encoders: Zend Safeguard, Sourceguardian PHP Encoder, ionCube PHP Encoder and phpShield.
Support
PHP has a formal development manual that is maintained by the open source community. In addition, answers to most questions can often be found by doing a simple internet search. PHP users assist each other through various media such as chat, forums, newsgroups and PHP developer web sites. In turn, the PHP development team actively participates in such communities, garnering assistance from them in their own development effort (PHP itself) and providing assistance to them as well. There are many help resources available for the novice PHP programmer.
Criticism
Criticisms of PHP include those general criticisms ascribed to other scripting programming languages and dynamically typed languages. In addition, specific criticisms of PHP include:
Syntax
- PHP does not enforce the declaration of variables, and variables that have not been initialized can have operations (such as concatenation) performed on them; however, an operation on an uninitialized variable does raise an E_NOTICE level error, errors that are hidden by default. This leads to security holes with register_globals (not on by default), as mentioned below. See also error_reporting().
- Within sections of the built-in function selection there is little or no consistency regarding argument order (examples: order of subject array and other data for array handling functions, order of needle and haystack in various search functions).
- Variables in PHP are not limited to one type. It is possible to assign an integer value to the variable $Q, then assign a string value, and then assign an array to it. This can often lead to difficult-to-debug code.
- Functions are also not allowed to (directly) force the types of their arguments. (PHP 5 improves on this, by adding a possibility to force a function argument to be an array or an object of a certain class.)
- Method/function overloading is not allowed.
- Type checking is not strict. In most languages "0" (the string "0") is not equivalent to 0 (the integer zero), which in turn is not equal to the value FALSE (which is the boolean value for 0). A workaround is using strict (===) type checking as opposed to loose (==), as in the example below:
<?php $intVar = 0; $strVar = "0"; $boolVar = FALSE; if ($intVar == $strVar && $boolVar == $strVar) { echo 'Values "0" and 0 are the same when non-strict comparisons are used'; } echo 'Instead, strict === comparisons must be used, which also check for type'; if ($intVar === $strVar) { echo 'This code will not be executed.'; } ?>
Built-in functions
- Built-in function names have no standard form, with some employing underscores (e.g. strip_tags, html_entity_decode) while others do not (e.g. stripslashes, htmlentities). Furthermore, some functions are verb_noun() while others are noun_verb() and some are prefixed_byModuleName while others use a module_suffix_scheme. Although all new functions do follow a naming standard, old names remain for backward compatibility reasons.
- Some functions have inconsistent output. Statements like This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". can be found in the documentation. This is related to PHP's dynamic typing. A workaround is using strict (===) type checking as opposed to loose (==). See also the manual on type juggling.
- The number of built-in functions is said to be too numerous, with many functions performing the same actions, but with just slightly different data, results, etc. This is said to make it difficult to program in the language without the frequent consultation of a reference work.
- There are over 3,000 functions, sharing the same global namespace. Most functions are not enabled by default, but become available when PHP is linked against the required libraries. To mitigate this, function names are usually prefixed with their library name.
- There is a "magic quotes" feature that inserts backslashes into user input strings. The feature was introduced to reduce code written by beginners from being dangerous (such as in SQL injection attacks), but some criticize it as a frequent cause of improperly displayed text or encouraging beginners to write PHP which is vulnerable to SQL-injection when used on a system with it turned off. (Always be sure to check for "magic-quotes":
get_magic_quotes_gpc();
and to unset "magic-quotes-runtime":set_magic_quotes_runtime(0);
.) Magic Quotes Runtime defaults to Off. The default Magic Quotes GPC setting is determined by which of the PHP ini files that you use. It is On by default in php.ini-dist, and Off in php.ini-recommended. For more information, see the security section in the Magic Quotes chapter of the PHP manual.
Security
- If register_globals is enabled in PHP's configuration file, PHP automatically puts the values of Post, Get, Cookie and Session Parameters into standard variables, which can be a significant security risk for scripts that assume those variables are undefined. As of version 4.2.0 register_globals defaults to off. For more information, see the security section in the Using Register Globals chapter of the PHP manual.
- Other languages, such as ASP.NET, include functionality to detect and clean harmful cross-site scripting or other malicious code automatically, whereas PHP does not. See also strip_tags().
- In the majority of cases, Linux and Unix webservers with PHP installed (using mod_php) typically run PHP scripts as "nobody", which can make file security in a shared hosting environment difficult. PHP's Safe Mode can emulate the security behavior of the OS to partially overcome this problem.
Miscellaneous
- Error messages are said to be confusing, although this is a common criticism levelled at many programming languages. For further information, see the manual section on PHP parser tokens. (PHP's error reporting when set to report all has especially useful tips. The only one that might be confusing to a new programmer is the one where it expects a semi colon at the end of your page. This is normally caused by not closing a brace somewhere in your code.)
- The many settings in the PHP interpreter's configuration file (php.ini) mean that code that works with one installation of PHP might not work with another. For example, if code is written to work with register_globals turned on, it won't work on another system that has register_globals turned off. This makes it necessary to write code that is cross-platform compatible by assuming that register_globals will be off and therefore calling a global variable with its prefix in front of its name, such as $_POST['variable'], $_SERVER['variable'] and $_COOKIE['variable']—not, simply, $variable. For more information, see the manual page on using external variables.
- Some PHP extensions use libraries that are not threadsafe, so rendering with Apache 2's Multithreaded MPM (multi-processing module) may cause crashes.
- There is no native support for Unicode or multibyte strings (mbstring is provided as an extension). This is an improvement planned for the next major revision (5.5 or 6.0). [12]
- A library has been developed called WASP or Web Application Structure for PHP that delivers a three-tier framework for PHP web applications more similar to other formal enterprise products like WLS (Web Logic Server) instead of PHP's usual script-style, code-hacker-friendly approach.
- PHP5 is not fully backward compatible with PHP4.
See also
References
- Jason E. Sweat. Guide to PHP Design Patterns. PHP|architect, 2005. ISBN 0973589825.
- Ilia Alshanetsky. Guide to PHP Security. PHP|architect, 2005. ISBN 0973862106.
- Chris Shiflett. Essential PHP Security. O'Reilly Media, 2005. ISBN 059600656X.
- Larry Ullman. PHP and MySQL for Dynamic Web Sites. Peachpit Press, 1st edition, 2003. ISBN 0321186486.
External links
This page or section may contain link spam masquerading as content. |
PHP.net (official PHP website)
- PHP: Hypertext Preprocessor
- Selected sub-pages of php.net:
- Selected sub-domains of php.net:
- PEAR: PHP Extension and Application Repository
- PECL: PHP Extension Community Library
- Smarty: Template Engine
- PHP-GTK extension providing an object-oriented interface to GTK+ classes and functions
- PHP Presents and PHP Conference Material Site — Sites collecting slides of talks given by well known people from the PHP community. The former one is also known as pres2 (version 2 of the latter).
Reference material
- Official PHP Documentation
- PHP Cheat Sheet - A quick reference for PHP
Security
- Sitepoint's Top 7 Security Blunders with PHP.
- The OWASP Top Ten Security Vulnerabilities as applied to PHP.
- PHP Security Consortium — International group of PHP experts dedicated to promoting secure programming practices.
- WACT PHP Application Security Wiki — The Web Application Component Toolkit's wiki page on PHP security resources.
- Hardened PHP Project — Group of security experts developing a modification to PHP to protect it against known and unknown attacks, dedicating themself to promote and teach secure PHP programming.
- PHP Impact of Vulnerabilities — Graphs showing the types of vulnerabilities that affect PHP.
Books
- PHP in a Nutshell
- Essential PHP Security
- PHP Book reviews — Reviews of PHP books and others of related interests
- PHP Book Reviews
Training
Support
- Forums
- DMOZ Open Directory
- Dev Network.
- Official PHP Support Page
- ThePHPGuy.com - PHP forums & Help
- PHP Freaks
- Dev Shed
- PHPBuilder
- Codewalkers
- User groups
- Directory of country specific PHP user groups, from the users of the PHP Classes site.
- New York PHP, the largest user group in North America (they maintain several active mailing lists).
- Blogs
- California
- OCPHP - Orange County PHP User Group(with a smile)
- Newsgroups / Usenet
- Chat / IRC
- Mailing lists / Listservs
Resources
- Open Directory Project:
- PHP for GUI Desktop Application Development
- PHP Classes — Ready to use PHP components in the form of classes of objects (registration required) and Book Reviews
- PHP Developer's Network
- PHP Editors and IDE Reviews - Website dedicated to PHP Editors and IDE's
- PHP Freaks
- SomeCoders
- PHP Frequently Asked Questions
- PHPXref.com: Use the Source - A repository of cross referenced PHP applications
- BioPHP.org - PHP for bioinformatics
- Codewalkers
Advocacy
- Experiences of Using PHP in Large Websites
- Making the Case for PHP at Yahoo! — Michael J. Radwin, Yahoo! Engineer explains why Yahoo! has chosen PHP over Apache mod_include, ASP, ColdFusion, Perl, JSP, Servlets, J2EE, XSLT and ClearSilver
- Follow-up: One Year of PHP at Yahoo!
- Newsforge report of Netcraft web host survey that says PHP is widely used
- The PHP Scalability Myth — Jack Herrington
- PHP Scales — Chris Shiflett