Software Development Resources
Create account | Log in | Log in with OpenID | Help

PHP

From DocForge

Revision as of 17:50, 24 August 2011 by Matt (Talk | contribs)

PHP is a high level interpreted language most frequently used in the creation of dynamic web sites but can also be used for the development of desktop GUI and command line applications. Its syntax draws upon elements found in C, Perl and Java, and, to a lesser extent, C++ and shell scripts. PHP supports both procedural programming and object oriented programming.

The PHP interpreter is run as a web server module, through CGI, or independently at the command line. It takes input from a file or stream containing text and special PHP instructions and outputs another stream of data for display. Since PHP version 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine. The Zend Engine II is the core of PHP 5.

Contents

Reference

Basic Syntax

A Hello World code example for PHP:

<?php
 echo 'Hello, World!';
?>

PHP only parses code within its delimiters, typically <?php ?>. Anything outside its delimiters is sent directly to output and not parsed by PHP. The example above outputs:

Hello, World!

The primary purpose of delimiting the code is to allow PHP statements to be embedded within HTML documents, for example:

<?php
 // PHP statements
?>
 Regular HTML
<?php
 // More PHP statements
?>

The short-tag configuration option simplifies the delimiters to be <? and ?>. This also alows for easy templating by defining variables above your output area with the <?= operand. For example:

<?php
  // Code
  $hello = "Hello World";
  // Code
?>

and then later in html:

<!-- lots of html -->
 <div>
  <p><?=$hello?></p>
 </div>

Variables are prefixed with a dollar symbol and a type isn't specified in advance. Variable names are case sensitive while function and class names are not. Both double-quoted ("") and heredoc strings allow the ability to embed a variable's value into a string.

PHP treats new lines as whitespace, in the manner of a free-form language (except when inside string quotes). Statements are terminated by a semicolon, except in a few special cases.

PHP has three types of comment syntax: /* */ which serves as block comments, and // and # which are used for inline comments.

Data Types

PHP stores whole numbers in a platform-dependent range. This range is typically that of 32-bit signed integers. Integer variables can be assigned using decimal (positive and negative), octal and hexadecimal notations. Real numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.

PHP has a native boolean type, named "boolean", similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values can be interpreted as true and zero as false, as in Perl.

The null data type represents a variable that has no value. The only value in the null data type is NULL.

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.

Arrays support both numeric and string indices, and are heterogeneous. 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.

Objects

Basic object oriented programming functionality was added in PHP 3. However, handling of objects was completely rewritten for PHP 5, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types. 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. PHP 5 introduced private and protected member variables and methods, along with abstract classes and abstract methods. It also introduced a standard way of declaring constructors and destructors similar to that of other object-oriented languages, such as C++, and an exception handling model similar to that of other programming languages.

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.

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.

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 such as embedded MySQL and SQLite, LDAP servers, and others. Many functions familiar to C programmers such as those in the stdio.h family are available by default.

Extension

PHP allows developers to write extensions in C to add functionality to the PHP language. These can then be compiled into PHP or loaded dynamically at runtime. 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. Some more unusual features include integration with IRC, and dynamic generation of images and Adobe Flash content. The PHP Extension Community Library (PECL) project is a repository for extensions to the PHP language.

Source Code Encoders, Optimizers and Accelerators

As with many scripting languages, PHP scripts are normally kept as human-readable source code, even on production webservers. While this allows flexibility, it can raise issues with security and performance.

Encoders offer some source code security and enable proprietary software by hindering source code reverse engineering. Encoders fall broadly into two types; those that hide source code and those that compile code into bytecode. The downside of this latter approach is that a special extension has to be installed on the server in order to run encoded scripts, however the approach of encoding compiled code and use of an extension offers typically the best performance, security and opportunity for additional features that may be useful for developers. Compiled code solutions may exploit the potential for increased security through the use of their own execution engine, although some simpler solutions rely on the regular PHP engine to execute the compiled code. The most commonly used packages for source code protection are from Zend Technologies and ionCube Ltd.

Code optimizers improve the quality of the compiled code by reducing its size and making changes that can reduce the execution time and improve performance. The nature of the PHP compiler is such that there are often many opportunities for code optimization.

Accelerators offer performance gains by caching the compiled form of a PHP script in shared memory to avoid the overhead of parsing and compiling the code every time the script is run. They may also perform code optimization to provide increased execution performance. Both commercial (e.g. Zend Platform) and open source accelerators (e.g. xcache, eAccelerator, APC) are available.

Debuggers and Profilers

Debuggers and profilers allow developers to analyze running PHP code for potential and noted software bugs and bottlenecks. Examples of such software for PHP include APD and Xdebug.

Templating Engines

Templating engines provide macros that allow PHP applications to uniformly identify common variables. One popular templating engine is Smarty.

PEAR

The PHP Extension and Application Repository (PEAR) project aims to provide reusable libraries and components for PHP development. PEAR projects are usually written in PHP code using the Object-oriented programming paradigm.


Common Methodologies


PHP Functions

In PHP, there are hundreds of built-in functions. You can create your own functions. A function will be executed by a call to the function. You may call a function from anywhere within a page.

// Define a custom function
function functionName() {
  [code to be executed]
}

To add more functionality to a function, you can define parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses. To let a function return a value, use the return statement:

<html>
 <body>
  <?php
    function add($x,$y) {
      $total=$x+$y;
      return $total;
    }
    echo "6 + 9 = " . add(6,9);
  ?>
 </body>
</html>

Page output:

<html>
 <body>
  6 + 9 = 15
 </body>
</html>


Useful Functions

Convert Decimal to Octal

Note: There is an internal function for this: decoct()

function decimal_to_octal($dec) {
    $result = '';
    do {
        $result = ($dec & 0x07).$result;
    } while (($dec >>= 3) > 0);
    return $result;
}

As of PHP 4, base_convert can be used to convert decimal to octal.

Convert Decimal to Binary

Note: There is an internal function for this: decbin()

This returns the binary version of a positive integer as a string.

function decimal_to_binary($dec) {
    $result = '';
    do {
        $result = ($dec & 0x01).$result;
    } while (($dec >>= 1) > 0);
    return $result;
}

As of PHP 4, base_convert can be used to convert decimal to binary.

Beginning/End-of-day Timestamps

Mark got me thinking about this, and then I was messing around with one of my own projects that needed the same feature, and i realized the easy way to do it.

I would always get the year/month/day out of a timestamp using the date() function, and then create a new UNIX timestamp with mktime().

I just realized the best way is:

$now = time();
$beginning_of_day = $now - ($now % 86400); // note: 86400 == 24*60*60

This works for me because I definitely remember that number for seconds in a day, and avoids any locale-dependent variations. plus, end of day becomes just as easy.

Note: time() is GMT (or UTC?), to get the equivalent in local time one might do:

$beginning_of_day = strtotime('midnight'); // local time
$beginning_of_day = strtotime('midnight GMT');
$beginning_of_day = strtotime('midnight UTC');

Formatting a Large Amount of Seconds

If you save dates in timestamp format, you may find a need to display the time difference between dates. The easiest way to do it in PHP isn't necessarily the most efficient, but it's a nice trick that's easy to read and maintain:

define('DAY', 86400);
$calculated_value = mktime(0,0,0,1,1,2000) + $value;
if($value > DAY * 365){
	$result .= date('y', $calculated_value);
	$result .= 'y ';
}
if($value > DAY * 30){
	$result .= date('n', $calculated_value);
	$result .= 'mo ';
}
if($value > DAY){
	$result .= date('j', $calculated_value);
	$result .= 'd ';
}
if($value > 3600){
	$result .= date('G', $calculated_value);
	$result .= 'h ';
}
if($value > 60){
	$result .= date('i', $calculated_value);
	$result .= 'm ';
}
$result .= date('s', $calculated_value);
$result .= 's ';

This code is pretty verbose for clarity, but it can be a lot briefer and more efficient. I needed to use this in a report where it was going to run once for each row, so I used this:

$parts = array('y'=>'y','n'=>'mo','j'=>'d','G'=>'h','i'=>'m','s'=>'s');
$parts = array_combine(explode(':', date(implode(':', array_keys($parts)), 
         mktime(0,0,0,1,1,2000) + $value)), array_values($parts));
$result = '';
foreach($parts as $num => $mark){
	if($num+0){
		$result .= "$num$mark ";
	}
}

Replacing "smart" quotes with "real" quotes

Microsoft Windows has a habit of replacing standard quotes with "smart" quotes, sometimes called "curly" quotes. Instead of falling straight down these quotes curl inward toward the text they enclose. These quotation marks aren't from the standard ASCII table. Therefore when they're copied and pasted into a web browser they often cause string issues with web server software. To convert these quotes to their standard ASCII equivalents their extended ASCII codes are needed. This PHP code will perform the required replacement:

$from = array(chr(145), chr(146), chr(147), chr(148));
$to = array("'", "'", '"', '"');
$string = str_replace($from, $to, $string);

Applications Written in PHP

See Also


Additional copyright notice: Some content of this page is a derivative work of a Wikipedia article under the CC-BY-SA License and/or GNU FDL. The original article and author information can be found at http://en.wikipedia.org/wiki/PHP.

Discuss