PHP notes PHP Notes

Overview & Perspective

PHP is a server-side, as opposed to client-side (e.g. JavaScript), scripting language. PHP provides a web-server tools interface.  Unlike an application server, PHP encourages using tools that scale, rather than requiring a central control process; there is no standalone PHP process, like the Java JVM, avoiding PHP becoming an architectural bottleneck.  PHP avoids dictating structural approach to the designer.

Architecture

Multi-tier architecture

The template view layer, typically, contains very little PHP — just function calls, includes and loops.   The most popular deployment-model for PHP is to link into the pre-forking multi-process Apache web server.  Like Perl & Python, PHP parses and executes scripts, directly.

Use a registry, instead of global variables

Since using Global variables has negative security implications, variables, including object instances, such as a database connection, can be, effectively, global in scope by implementing a registry class … with Set, Get and unSet methods.

Features

PHP can be used on all major operating systems and with many databases, including ODBC databases.
PHP communicates through many service protocols.
PHP is strong at text processing, including XML.

Server-side scripting

What distinguishes PHP from client-side JavaScript (used for client-side scripting) is that the code is executed on the server.  The client receives the results of running that script with no way of determining what the underlying code may be.  You can configure your web server to process all your HTML files with PHP; then, there's really no way that users can see your code.

PHP script uses

PHP is probably not the very best language to write windows applications.  PHP-GTK is an extension to PHP for writing GUI clients.

xForms

a webForms variation for a wider variety of applications.

xForms renders as XML.  In a normal HTML form, the data would be sent as application/x-www-form-url-encoded; in an XForm information is sent formatted as XML data.

In the $HTTP_RAW_POST_DATA variable you'll find the XML document, generated by the browser, which you can pass into your favorite XSLT engine or document parser.

How PHP runs …

On Apache, a multi-process http server, PHP can run as a PHP Apache module or as PHP-CGI. 
On Windows, PHP runs as a CGI wrapper module; a PHP instance is created/destroyed for every PHP page request (How efficient and scalable is this?).

PHP Extensions

The compiled PHP version can be extended via .dll extensions.  The extensions directory is specified by extention_dir, obviating the need to specify extension paths.  Extensions are loaded (e.g. upon Apache startup) when un-commented in php.ini.   Alternatively, PHP extensions can be loaded, dynamically (at runtime), using dl(‘libraryName.dll’).

Persistent connections

When opening a persistent connection, every following page, requesting SQL services, can re-use the same established SQL server connection.  Persistent connections are efficient, if the overhead to create a link to your SQL server is high (scalable?).

PHP concepts & syntax

Any form element (in a form) will automatically be available to your PHP scripts.
Variables are prefixed with a dollar-sign in PHP (e.g. $variableName).

PHP History

According to Rasmus Lerdorf, the original author, PHP originally stood for “Personal Home Page Tools”.  PHP is, now, said to be a recursive acronym, standing for PHP Hypertext Processor. 

Israelis, Zeev Suraski and Andi Gutmans, wrote the version 3 (released in mid 1998) parsing engine and called it Zend (a combination of Zeev and Andi).

PHP is designed to solve web problems.  Functions are not case-sensitive; variables are.  PHP never does any kind of (data) type checking; you have to run type conversion functions on every function parameter.

PHP syntax draws upon C, Java & Perl. 

Forms tips

For David Sklar tips, see: http://www.onlamp.com/pub/a/php/2004/08/26/PHPformhandling.html

Pear HTML_QuickForm

HTML_QuickForm frees you from the grunt work of displaying form element defaults, encoding HTML entities and duplicating validation code.  Its built-in layout engine is customizable and you can integrate with template engines, like Smarty.

The value of using PEAR's HTML_QuickForm comes with validating and applying automated data filtering via rules and filters.  Mixed HTML and PHP forms can lack clarity, compared to pure PHP forms.

Using the same name for both database fields and form element names greatly simplify populating default values and, later, building the SQL UPDATE statements. See: http://www.onlamp.com/pub/a/php/2004/07/22/html_quickform.html

Installation

XAMPP

The easiest PHP (and Apache and MySQL) Windows installation is provided by the ApacheFriends.org distribution, called “XAMPP”.  XAMPP can be installed to make no Windows Registry entries.  The whole directory structure can be deleted – for replacement with newer versions.

XAMPP quickstart

On Windows, just unzip to C:\xampp and run the C:\xampp\setup_xampp.bat file; then, start it via C:\xampp\xampp_start.exe (Make a desktop icon for the latter – to start it, when desired).

Though there are XAMPP distributions for Linux, K/Ubunutu can just apt-get install Apache, PHP and the NetBeans IDE.

PHP.ini

configuration

PHP.ini path

Apache PHP

\xampp\apache\bin\PHP.ini

CGI mode PHP

\xampp\php\PHP.ini

PHP Expert Editor (which uses PHP CLI)

\xampp\php\PHP.ini

Apache root directory

The XAMPP Apache root directory is \xampp\htdocs\ (see ApacheNote.doc)

A “virtual folder” may be located anywhere in the file system, as long as a \xampp\apache\conf\httpd.conf Alias entry points to that virtual directory; for example (# note: forward slashes are required even to specify the Windows path!),
  Alias /tshirtshop/ "C:/tshirtshop/"
  Alias /tshirtshop   "C:/tshirtshop"
can be called as:      http://localhost/tshirtshop

The Alias is case sensitive, because, like the forward slashes for Windows, it’s, basically, a *nix program.

Apache won’t start …

If you see the following error:
 "Only one usage of each socket address (protocol/network  address/port) is normally permitted.
: make_sock: could not bind to address 0.0.0.0:443 no listening sockets available, shutting down"
It is because SkyPE options -> Connection -> "Use port 80 and 443 as alternatives for incoming connections" is checked.

PHPcli.exe

PHPcli.exe refers to an old PHP Command-Line Interface version; PHP 5 version is simply named php.exe and is located at \xampp\php\php.exe.
However, Xampp doesn’t place the CLI version in a \cli folder; it’s in \xampp\php\php.exe.

PATH requirements

Add C:\xampp\php to the Windows PATH – to use the CLI version.

If you do not have access to PHP.ini (e.g. in a web hosted environment), you have to set the include_path in each PHP script or via ini_set().

If you do have PHP.ini access, add to the include_path, as necessary e.g. to add a path to the Zend Framework library, add the following to: C:\xampp\apache\bin\php.ini … include_path:
  ;c:\xampp\htdocs\protected\ZendFramework-trunk\library\
… where ;c:\xampp\htdocs\protected\ZendFramework-trunk\library\ is the location of your Zend Framework \library\Zend\ directory. 
Notice that the \protected\ directory in the above example is under the web root … a “no no”.  If your (cheap) web host won’t provide a non-web root directory, you have to use what you’ve got and protect it e.g. via an .htaccess file with “Deny from all” in it.

security permissions

Instructions, referring to the User, running the (Apache) web server, mean the User, “Everyone”.  “Everyone” needs read permissions on C:\xampp\apache\bin\php.ini.

How to adjust security permissions on XP

To access permissions with XP, you can’t use “simple file sharing”; go to Explorer -> Tools -> Folder Options -> View (tab) … and at the bottom of the list un-check “Use simple file sharing (Recommended).
Click the “Advanced” button and for “Everyone” check “Replace permission entries on all child objects with entries shown her that apply to child objects.”

Pear configuration with Xampp

See PearNotes.html – to avoid duplication in this document.

PHP5 for Windows Server 2003 IIS 6

IIS 6 is locked down tighter (than previous IIS versions) and defaults to only allowing static web pages.  That PHP was written for *nix might explain reported frustrations with running PHP on IIS.

PHP offers two Windows versions:
  1. CGI (php-cgi.exe)
  2. SAPI (Server API) (php5isapi.dll), said to provide faster performance than the CGI version. 
The ISAPI filter module (php5isapi.dll) enables ISAPI-compliant servers, namely IIS.  Using the PHP ISAPI filter, php5isapi.dll, requires HTTP authentication; if completing the user/password dialog box is unacceptable, don’t use the php5isapi.dll ISAPI filter i.e. the alternative is to use the CGI php-cgi.exe.

PHP.ini

Use php.ini-recommended for production-level security; use php.ini-dist for development-level security.  Copy C:\php\php.ini-dist to C:\php\php.ini i.e. copy & change its name to php.ini.  Edit php.ini, as follows:
  doc_root = "C:\Inetpub\wwwroot"    {i.e. to IIS root directory}
extension_dir = C:\php\ext         {no quotes & no backslash after ext }
Only if using CGI, un-comment and set: cgi.force_redirect = 0  {Otherwise, an HTTP 400 error will result.}

Un-commenting extension=php_mysql.dll generated a “File not found” error, despite trying variations on the “extension_dir” setting.  I suspect that this is due to PHP5 built-in mysql capability.

IIS Manager

File system permissions

Right-click C:\php -> Properties -> Security (tab) -> Add … (button) -> Advanced (button) -> Find Now (button) … and add the IUSR_machineName account.

For PHP to operate most activities, write and execute permissions will be needed – in addition to read permission.  In the bottom-right of the main Properties, click the “Advanced” button and at the bottom of the next “Advanced Security Settings …” check “Replace permission entries on all child objects with entries shown here that apply to child objects”.

According to install.txt, PHP searches for php.ini in the following locations (in the following order):
  1. PHPIniDir directive (Apache 2 module only)
  2. HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath
  3. The PHPRC environment variable
  4. PHP directory (for CGI) or the web server's directory (for SAPI modules)
  5. Windows directory (C:\Windows or C:\WinNT)
To keep the installation in a single location (and for ease in upgrading), add a new PHPRC environment variable, as follows:

Re-start IIS

IIS may need to be stopped (> net stop iisadmin) & re-started (> net start w3svc).

In a new installation it is advisable to first get PHP working and tested (without any extensions) before enabling extensions (by un-commenting extensions) in php.ini.

Rock & roll

Try out your favorite PHPinfo() file …

PHP language basics & syntax

Escaping HTML … (<?php. . .?> and <script language="php">. . .</script>) … <?php. . .?> form to conform to the XML.
Comments Persistent database links are not destroyed by the garbage collector.

Function names are not case sensitive.

Prefix Private functions with an underscore e.g. _functionName().

Type PHP assigns type at runtime.  Type may be cast.

Variables PHP summary

Acronyms & terms

Zend Engine (Zend being a combination of Zeev and Andi).  One of the PHP authors is Zeev Suraski; another is Andy Gutmans.

Arrays

Array values may be fetched via zero-based, bracketed ordinal values e.g. Associative arrays have key names in addition to values i.e. key-value pairs.  The PHP array_keys() and array_values() functions may be used to uncover array keys and values, when array content is unknown.  The sizeof() function returns the number array members (to curtail looping), as follows:
     $form_names =  array_keys($_GET);
    $form_values =  array_values($_GET);

    for ($i = 0; $i <  sizeof($_GET); $i++)

    //  … or one could use a foreach() loop.
    foreach ($_GET as $key=>$value) …

Assignment (=) vs. comparison (==) vs. (===) identical

Boolean ‘and’ (&&)

Classes

To create a class:
  Class className
  {
  	//  does whatever …
}
The Implements keyword refers to implementing a class interface. $this, usually, refers to the object to which the calling method belongs.  However, $this can refer to a different object, if the method were called, statically.

Self refers to the current class (e.g. self::$className). Self and parent are valid new operator arguments e.g. new self … or new self() … or new parent.

Classless objects

To create (instantiate) an object and add properties to the object – without defining a class,
  $objectName = new stdClass;
$objectName->propertyName = ‘propertyValue’;
Just as the array( ) function returns an empty array, creating an object of the type stdClass provides an object without properties or methods.  stdClass is the PHP’s base class from which all classes are extended.  Object methods or properties can’t be defined after an object is instantiated. 

Empty objects, with attributes set at runtime (rather than being declared as part of the class) can be used to create stdClass objects when a function returns a generic object (e.g. returned from a database fetching function), without actually making a database request.  For example, stdClass type objects can be used as run-time configuration/information repositories, instead of variables or arrays, for SET and GET capability.  Drawbacks:

Constants

Use all capitals and no $variable preface.  Once defined, trying to change a constant during the script life will generate an error.
	Define(“CONSTANT_NAME”, “the constant’s value”);

Data access

A database abstraction layer (e.g. Pear::DB) hides the RDBMS; a data-access layer (e.g. PHP DataObjects) permits using the same commands - even if the data source is switched. DataObjects might use Pear::DB, instead of PHP's native database functions. If you know that the chances of changing the underlying RDBMS are next to nil, forego using Pear::DB.  Pear::DB adds a layer of abstraction that slows code execution … and PHP's native DB functions operate faster. Creating a separate class for each table leads to difficult joins.

Prepending DataObject class names with DO_ simulates PHP namespaces.

The new PHP 5 Reflection API retrieves class/object information.

Once the DataObjects layer is created, the coder can interact with the database, using only PHP code i.e. not SQL.

Pear::DB_DataObject involves more learning curve.  Propel is another alternative.

For specific examples, see: http://www.onlamp.com/pub/a/php/2004/08/05/dataobjects.html

MySQLi  interacts, natively, with MySQL via an object-based approach.

Environment variables

Since globals and the old _ENV variables are considered less secure, the current approach is to use the following:
  $_SERVER['VARIABLE_NAME']
  $_SERVER['DOCUMENT_ROOT']

Errors

try
{ // go ahead and try something! } catch (Exception $e) { echo $e->getMessage(), "\n"; }

Files & paths

__FILE__ returns full operating system path and currently-running filename
realpath() returns full operating system path and currently-running filename (as does __FILE__ )
dirname() returns full operating system path - without the currently-running filename
$_SERVER['PHP_SELF']) returns the full webhost directory path and currently-running filename
dirname($_SERVER['PHP_SELF'])) returns the full webhost directory path to the currently-running filename - sans filename
basename() returns the currently-running (calling) filename
basename(dirname(__FILE__)) returns the folder (directory) of the currently-running (calling) filename
pathinfo() returns an array, containing keys for dirname, basename, extension, filename

A nice file uploading example is available from IBM: https://www6.software.ibm.com/developerworks/education/os-phptut2/section3.html

Security

An .htaccess file in any directory, containing the following line, will hide scripts from browser listings.
	Deny from all

Including files

Normally, include libraries by un-commenting them in PHP.ini. In web hosting environments dl() may be helpful to load a library from the PHP script. Though dl() has been deprecated and won't work on a multi-threaded web server, it will work with the php-cgi encountered in a share web hosting environment.

Magic_quotes and register_globals

To turn off magic_quotes, without PHP.ini access, add this to .htaccess
  php_value magic_quotes_gpc 0
Magic_quotes is scheduled for deprecation in PHP6.

To turn off register_globals:
  php_value register_globals 0

Printing (to browser) ... often used for elementary debugging

Foreach() loop printing

print_r($array);			// prints array key-values
print_r($object);			// prints object components


// Wrap print_r() calls in “<pre>” …  “</pre>” - to designate pre-defined  (non-paragraph) text.

Print “<pre>”; foreach(query as $row) { Print_r($array); Print_r($object); } Print “</pre>”;

Print object contents to browser – without foreach()

The following are handy – to verify what you’ve really got in an object.

 var_dump($arrayName);
or var_dump($objectName); or Print "<pre>"; print_r(get_object_vars($someObject)); Print "</pre>"; Echo(); Print(); <?=PAGE_TITLE ?>
Note:  the = sign in the last statement obviates using either echo() or print().

Quotes

Enclose text in single quotes and concatenate it with your variables; this saves processing because text in single quotes is not scanned for variables.

Sessions

Session_start() must be called before anything is sent to the browser.  To log a user out of a Session:
  unset($_SESSION["userName"]);
To conclude a Session:
  session_destroy();

SPL (Standard PHP Library)

SPL provides standardized object-oriented interfaces.  Currently, the Iterator design pattern is implemented in the SPL.  An Iterator provides sequential access (like a database forward-only cursor) to an object’s elements - to traverse (i.e. loop/iterate over) aggregate structures (e.g. arrays, database result sets, xml trees, directory or file listings … or any list).

SPL is specified in the PHP docs http://www.php.net/manual/en/ref.spl.php
For perspective, background and a good introduction to SPL and Iterators, check the article links in Section #9 at the bottom of this page:  http://www.php.net/~helly/php/ext/spl/

A directory Iterator

To list root directory files:
try
{
	foreach(new DirectoryIterator('./') as $Item)
	{
		echo $Item .	'<br>';
	}
}

catch(Exception $e)
{
	echo 'No files Found!';
}
To list a different directory, change … './' … to the desired path.

A directory file lister …

<?php

class fileLister extends DirectoryIterator
{
	function __construct($path)
    {
		parent::__construct($path);
	}

	function current()
	{
		return  parent::getFileName();
	}

	function valid()
    {
		if(parent::valid())
	{

if (!parent::isFile())
{
	parent::next();
	return  $this->valid();
}
	return TRUE;
}
	return FALSE;
}

function rewind()
{
	parent::rewind();
}
} // end class parenthesis

// List the directory files …
try
{
    // Instantiate a  fileLister object
    $fileList = new  fileLister('./');

    // Loop through the  directory files
    foreach ( $fileList as $directoryFile  )
    {
        echo $directoryFile.'<br />';
} } // end try parenthesis catch(Exception $e) { echo 'No files Found!<br />'; } // end catch parenthesis ?>

Symbols

MVC – Model View Controller architecture

A nice MVC overview tutorial is available at: http://www.phpit.net/article/simple-mvc-php5

MVC won't render static links within the overall view template; thus, it's best with MVC to stick with the MVC designe approach, consistently.

Page Controller pattern

The Front Controller specifies where to go (the URI page to fetch), while a Page Controller decides what to do (the action to perform - the class method to execute). The Front Controller doesn't realize it's dispatching a Page Controller and the Page Controller doesn't know what called it.  They work without knowledge of one another.

One reason to use a Front Controller with a Page Controller is to minimize duplicated view page content. The Front Controller can set up common menu bars, footers etc., while the Page Controller handles a specific request.  Separating logic and display makes it easier to fix bugs and make changes.
Implementing a Page Controller involves dispatching a view page and storing data.  The PHP include() function dispatches, like the Java RequestDispatcher#forward() function passes control from a servlet to a JSP.

View page logic should be limited to formatting data, provided by the controller.  Place data in a variable that both the controller and views can access.  For example, the controller might put view data in the array, $viewData; view pages will call this same variable.

Data model pattern

A model is responsible for data source interaction and providing data to the Controller. One implementation loads a request-specific model.  Alternatively, a data abstraction layer, may interact with the data source, directly.

Performance

Cache tools

xDebug

Tips in this article:
http://www.sitepoint.com/blogs/2007/04/23/faster-php-apps-profile-your-code-with-xdebug/

PDO (PHP Data Objects)

SQLite path connection

While the docs only mention providing an absolute path, immediately following the colon, following the database driver DSN, like this:
  $dbConnection = new PDO('sqlite:/path/to/SQLiteDbFile.sql3’);
I was able to specify the file path, elsewhere (e.g. to use the connection within a class function), like so:
    $SQLiteFile = $_SERVER[DOCUMENT_ROOT] .  '/someDirectory/SQLiteDbFile.SQL3';
$dbConnection = new PDO('sqlite:' . $SQLiteFile );
On Windows, the drive letter wasn’t necessary i.e. just the path.

Persistence & closing

PDO connections persist for script life unless ATTR_PERSISTENT => true.  PDO connections may be explicitly closed by assigning NULL to the connection.
  $dbConn = NULL
Persistent connection cache precludes the overhead of establishing a database connection for every script run on the website.  Some database drivers support ODBC connection pooling, which can share database connections with other/external process modules; if available, ODBC connection pooling requires establishing fewer database connections than PDO ATTR_PERSISTENT.

Prepared statements and stored procedures

Prepared statements parameters don’t need to be quoted; the PDO driver handles parameter quoting. Prepared statements preclude SQL injection.
  $preparedStatement = $dbConn->prepare(‘whatever SQL command’)

PHPdocumentor configuration

For large (e.g. CMS) projects, PHPdocumentor can take over a half hour, pegging the cpu and using up to 1 Gig of memory; PHPXref (see below) takes only a minute, not pegging the cpu and not using much memory.

After PEAR is working (e.g. via go-pear.phar), the following installs the latest PHPdocumentor:
  pear install –-onlyreqdeps channel:		// for example, pear.php.net/phpdocumentor-1.3.0RC3
Since Pear fetches from a *nix box, the “RC” part is case-sensitive. 

The PHPdocumentor installation notified me it depends on XML_Beautifier, which I installed via:
  pear install –-onlyreqdeps XML_Beautifier
Running:
  pear remote-info phpdocumentor
provided the following guidance:

Pear’s web interface requires that Apache see Pear’s data_dir, as a subdirectory of /htdocs (or an Apache httpd.conf Alias to the PEAR data_dir) directory.  The PHPdocumentor web interface is produced via: http://localhost/peardata/PhpDocumentor
… assuming that peardata is the Alias name for C:\php5\pear\data.  Save yourself some head-scratching by making include_path in both php.ini’s (i.e. for Apache and for CGI) point to the same pear\data.

PHP Expert IDE debugging configuration

PHP Expert uses NuSphere PHP_dbg.dll to debug.  You must configure the server part of PHP Debugger (via PHP.ini); the Client Part is integrated into PHP Expert Editor IDE.

The PHP_dbg.dll version MUST match the XAMPP PHP version (at least the compile dates must match).

PHP.ini specifies the extensions directory as:
  extension_dir = "C:\xampp\php\ext\"

… and it will prefix whatever’s after extension= … with C:\xampp\php\ext\

Download the free "Expert Debugger" from http://ankord.com

Install Expert Debugger and copy the version of php_dbg.dll from C:\Program Files\Expert Debugger\DBG\PHP_DBG.DLL\ to C:\xampp\php\ext\

Append the following to the \XAMPP\Apache\bin\PHP.ini extensions section:

  extension=php_dbg.dll-5.2.x

Comment-out the following lines, since Apache will crash at: http://localhost if Expert Debugger and Zend Optimizer are both enabled in PHP.ini

    [Zend]
    ;zend_extension_ts = "C:\xampp\php\zendOptimizer\lib\ZendExtensionManager.dll"
    ;zend_extension_manager.optimizer_ts = "C:\xampp\php\zendOptimizer\lib\Optimizer"
    ;zend_optimizer.enable_loader = 0
    ;zend_optimizer.optimization_level=15

Add the following somewhere after the extention= line (e.g. at the bottom of PHP.ini):

  [debugger]
  debugger.enabled = true
  debugger.profiler_enabled = on
After saving PHP.ini and re-starting Apache, PHPinfo() will display:

dbg

DBG php debugger, version 2.15.5, Copyright 2001, 2007, Dmitri Dmitrienko, www.nusphere.com

Version

2.15.5

Linked

as a shared library.

Profiler

compiled, disabled

Directive

Local Value

Master Value

debugger.enable_session_cookie

On

On

debugger.enabled

On

On

debugger.fail_silently

On

On

debugger.ignore_nops

Off

Off

debugger.JIT_enabled

Off

Off

debugger.JIT_host

127.0.0.1

127.0.0.1

debugger.JIT_level

3

3

debugger.JIT_port

7869

7869

debugger.profiler_enabled

On

On

debugger.session_nocache

On

On

debugger.timeout_seconds

300

300


Within PHP Expert IDE (from Ankord.com), A debugger intl3_svn.dll error (after installing TortoiseSVN), seems due to “Expert Debugger” (available at http://Ankord.com) internal web engine i.e. the error disappeared when choosing to render web pages via external Apache.

For more on PHP debugging, see: http://www.onlamp.com/pub/a/php/2004/08/12/DebuggingPHP.html
To include an array in debugging output, use var_dump() which prints all array elements.  Surround the var_dump() output with HTML <pre></pre> tags to have it nicely formatted (i.e. readable in other than paragraph form) in your web browser.

Debugging with Zend extensions

To use ZendOptimizer or other Zend extension(s), un-comment them in the [Zend] section, near the bottom of PHP.ini:
  zend_extension=/path/to/PHPextensions/php_dbg.dll

PHPXref Perl documenting configuration

PHPXref is a Perl-based, less cpu & memory intensive and less tag-dependent alternative to PHPdocumentor.  PHPXref doesn’t require the code-tagging, required by PHPdocumentor. For large (e.g. CMS) projects, PHPdocumentor can take over a half hour, pegging the cpu and using up to 1 Gig of memory; PHPXref takes only a minute, not pegging the cpu and not using much memory. PHPXref uses phpxref.cfg, instead of command-line, to specify source, target and other parameters. Edit phpxref.cfg for your objectives each time you have a different target project.

For Perl, forget the Xampp distribution, which includes no Perl modules; instead, install the ActiveState ActivePerl distribution (.msi – not the AS version) at: http://www.activestate.com/Products/ActivePerl/  Better yet, there’s a Windows version that includes Perl in a .zip file. Download it, here:  http://phpxref.sourceforge.net/. Readme.html includes “QuickStart” directions.

Scheduling

One can use the operating system task scheduling (cron, at etc.) to run a batch file, like:
  php whatever.php
… containing code to be executed outside your website.

Unit testing with PHPunit

From: http://www.onlamp.com/pub/a/php/2005/12/08/phpunit.html
by Sebastian Bergmann who wrote PHPunit.
"PHPUnit is a family of PEAR packages (PHPUnit, PHPUnit2) that I designed after proven Java solutions (JUnit, junitour, and TestDox)".  Install PHPunit, using the PEAR Installer: 
  pear install PHPUnit2
A failure is a violated PHPUnit assertion; an error is an unexpected exception or a PHP error.  Errors tend to be easier to fix than failures.  If you have a big list of problems, it is best to tackle the errors first and see if you have any failures left when you have fixed the errors.

Web Services with PHP

The following XML processing overview article is excellent and (mercifully) succinct:
     http://www.zend.com/php5/articles/php5-xmlphp.php

DOM

DOM (Document Object Model) is a W3C standard for representing XML data as an objects hierarchy.  The PHP5 DOM implementation corresponds to the W3C DOM object-based API specification, available at http://www.w3.org/DOM. The DOM standard is a verbose, trying to anticipate every imaginable situation.  “Nodes” are analogous to rows in database parlance. A nice IBM PHP DOM XML example is at: https://www6.software.ibm.com/developerworks/education/os-phptut2/section5.html

HTML 4

In addition to being able to load HTML documents the PHP DOM extension can also save them as HTML 4.  Use $dom->saveHTML() after you have built up your DOM document.

nuSoap

example:
<?php
    require_once('webservice.php');
    $ThisWS = WebService::ServiceProxy("http://localhost:8080/SoapService.wsdl");
    $ReturnValue = $ThisWS->[RemoteMethodName]("[RemoteMethodParameter]");
?>

PEAR SOAP

Most web services support SOAP requests; for example:
<?php
include('SOAP/Client.php'); $SOAPClient = new SOAP_Client("http://localhost/SOAP/example/server.php"); $SOAPOptions = array ( 'namespace'=> 'urn:SOAP_Example_Server', 'trace'=>1 ); $sEquation = $SOAPclient->call ( "echoString", $params = array ( "inputString" => "21 divided by 7 equals: " ), $SOAPOptions ); $sResult = $SOAPclient->call ( "divide", $params = array ( "dividend" => "21", "divisor" => 7 ), $SOAPOptions );  ?>

REST (Representational State Transfer)

REST calls are made over HTTP, like an HTML web service; parameters are specified in the query string.  On both the client and the server, there's HTTP header configuration.  A REST.PHP script responds with an XML (or other document); XSLT may transform the XML to HTML for browser rendition.  REST offers control, which means handling the results, yourself.

SimpleXML

SimpleXML allows developers to access XML files as if they were native PHP objects.

XML

For perspective on PHP XML processing, read: http://www.zend.com/php5/articles/php5-xmlphp.php
For XML tutorials, read: http://www.w3schools.com/xml/default.asp

XML Namespaces

xmlns:namespacePrefix="namespaceURI"

XML-RPC

XML-RPC is gaining popularity vs. SOAP, particularly in multi-server environments, because XML-RPC excels at enabling components, distributed across multiple servers, yielding performance advantages; for example:
<?php
    require_once 'XML/RPC.php';
    $sParameters = array(new XML_RPC_Value("Hello  World", 'int'));
    $msg = new  XML_RPC_Message("MyWebService.MyFunction", $sParameters);
    $client = new XML_RPC_Client("/RPC2",  "localhost", 80);
    $response = $client->send($msg);
    $v = $response->value();
?>

XPath

XPath is analogous to SQL for XML.  XPath allows querying an XML document for a specific node, matching some criteria.  XPath is much easier to use, faster in execution and requires less code than the standard DOM methods. Using XPath with SimpleXML saves a lot of typing (more succinct code).

XSL

Extensible Stylesheet Language (XSL) was designed for the need for an XML-based (as opposed to HTML-based CSS) stylesheet language.  XSL describes how an XML document should be displayed.  More Than a style sheet language XSL consists of:

XSLT

XSLT is the XML transformation portion of the XSL specification (the remaining XSL specifications are XSL-FO and XPath).  XSLT is a 1999 W3C recommendation. An XSLT stylesheet is used to transform an XML document into another document e.g. another XML document, PDF, HTML, RTF, TeX, delimited files, binary files or any other format that the XSLT processor is capable of producing. XSLT processing often begins by reading a serialized XML input document into the source tree and ends by writing the result tree to an output document.

XSLT PHP history

Two XSLT processors were implemented in PHP 4: The two APIs were not compatible; their feature sets were different. In PHP 5, only the libxslt processor is supported.  Libxslt was chosen because it is based on libxml2 and fits into the XML concept of PHP 5.  libxslt is one of the fastest XSLT implementations available (execution speed can be double that of Sablotron).

Sablotron

Sablotron is an XSLT, DOM and xPath processor, incorporated in PHP since PHP version 0.36 in 2000.  The goal of the Sablotron project is to create a lightweight, reliable and fast XML library processor, conforming to the W3C specification, freely available for public use as a base for multi-platform XML applications.  Sablotron is written in C++ to keep it as portable as possible.

SideBar Manager

… to manage sidebar column contents Business systems design, programming & integration

Templating

A good, brief PHP Templating guide is: http://allyourtech.com/content/articles/29_06_2005_templating_with_php.php If the template file is named .htm, the .php components will show in "show Source" and PHP will NOT be interpreted - only HTML will be interpreted by the web server. If the template file is named .php, the .php components won't show in "show Source" and both PHP and HTML will be interpreted by the web server.

Back Home