Chapter 18. PHP on Disparate Platforms

There are many reasons to use PHP on a Windows system, but the most common is that you want to develop web applications on your Windows desktop. PHP development on Windows is just as doable these days as it is on a Unix platform. PHP plays very well on Windows, and PHP’s supporting cast of server and add-on tools is just as Windows-friendly. Having a PHP system working on any of its supported platforms is simply a matter of preference. Setting up and developing with a PHP environment on Windows is very easy to do, as PHP is extremely cross-platform friendly, and installation and configuration are becoming simpler all the time. The relatively recent appearance on the market of Zend Server CE (Community Edition) for multiple platforms has been a wonderful help in establishing a common installation platform on all the major operating systems.

Writing Portable Code for Windows and Unix

One of the main reasons for running PHP on Windows is to develop locally before deploying in a production environment. As many production servers are Unix-based, it is important to consider writing your applications so that they can operate on any operating platform with minimal fuss.

Potential problem areas include applications that rely on external libraries, use native file I/O and security features, access system devices, fork or spawn threads, communicate via sockets, use signals, spawn external executables, or generate platform-specific graphical user interfaces.

The good news is that cross-platform development has been a major goal as PHP has evolved. For the most part, PHP scripts should be ported from Windows to Unix with few problems. However, there are instances where you can run into trouble when porting your scripts. For instance, some functions that were implemented very early in the life of PHP had to be mimicked for use under Windows. Other functions may be specific to the web server under which PHP is running.

Determining the Platform

To design with portability in mind, you may want to first test for the platform on which the script is running. PHP defines the constant PHP_OS, which contains the name of the operating system on which the PHP parser is executing. Possible values for the PHP_OS constant include "HP-UX", "Darwin" (macOS), "Linux", "SunOS", "WIN32", and "WINNT". You may also want to consider the php_uname() built-in function; it returns even more operating system information.

The following code shows how to test for a Windows platform:

if (PHP_OS == 'WIN32' || PHP_OS == 'WINNT') {
 echo "You are on a Windows System";
}
else {
 // some other platform
 echo "You are NOT on a Windows System";
}

Here is an example of the output for the php_uname() function as executed on a Windows 7 i5 laptop:

Windows NT PALADIN-LAPTO 6.1 build 7601 (Windows 7 Home Premium Edition Service Pack 1) i586

Handling Paths Across Platforms

PHP understands the use of backward or forward slashes on Windows platforms, and can even handle paths that use both. PHP also recognizes the forward slash when accessing Windows UNC paths (i.e., //machine_name/path/to/file). For example, these two lines are equivalent:

$fh = fopen("c:/planning/schedule.txt", 'r');
$fh = fopen("c:\planning\schedule.txt", 'r');

Sending Mail

On Unix systems, you can configure the mail() function to use sendmail or Qmail to send messages. When running PHP under Windows, you can use sendmail by installing it and setting the sendmail_path in php.ini to point at the executable. It is likely more convenient, however, to simply point the Windows version of PHP to an SMTP server that will accept you as a known mail client:

[mail function]
SMTP = mail.example.com ;URL or IP number to known mail server
sendmail_from = [email protected]

For an even simpler email solution, you can use the comprehensive PHPMailer library (https://github.com/PHPMailer/PHPMailer), which not only simplifies sending email from Windows platforms but is completely cross-platform and works on Unix systems as well.

$mail = new PHPMailer(true);

try {
 //Server settings
 $mail->SMTPDebug = SMTP::DEBUG_SERVER;
 $mail->isSMTP();
 $mail->Host = 'smtp1.example.com';
 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
 $mail->Port = 587;

 $mail->setFrom('[email protected]', 'Mailer');
 $mail->addAddress('[email protected]');

 $mail->isHTML(false);
 $mail->Subject = 'Here is the subject';
 $mail->Body = 'And here is the body.';

 $mail->send();
 echo 'Message has been sent';
} catch (Exception $e) {
 echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

End-of-Line Handling

Windows text files have lines that end in , whereas Unix text files have lines that end in . PHP processes files in binary mode, so it does not automatically convert from Windows line terminators to their Unix equivalents.

PHP on Windows sets the standard output, standard input, and standard error file handlers to binary mode and thus does not do any translations for you. This is important for handling the binary input often associated with POST messages from web servers.

Your program’s output goes to standard output, and you will have to specifically place Windows line terminators in the output stream if you want them there. One way to handle this is to define an end-of-line constant and output functions that use it:

if (PHP_OS == "WIN32" || PHP_OS == "WINNT") {
 define('EOL', "
");
}
else if (PHP_OS == "Linux") {
 define('EOL', "
");
}
else {
 define('EOL', "
");
}

function ln($out) {
 echo $out . EOL;
}

ln("this line will have the server platform's EOL character");

A simpler way of handling this is through the PHP_EOL constant, which automatically determines the end-of-line string for the server’s system. (Note, however, that the server system and the desired EOL marker may not be the same in all cases.)

function ln($out) {
 echo $out . PHP_EOL;
}

End-of-File Handling

Windows text files end in a Control-Z (x1A), whereas Unix stores file-length information separately from the file’s data. PHP recognizes the EOF character of the platform on which it is running; thus, the feof() function works for reading Windows text files.

Using External Commands

PHP uses the default command shell of Windows for process manipulation. Only rudimentary Unix shell redirections and pipes are available under Windows (e.g., separate redirection of standard output and standard error is not possible), and the quoting rules are entirely different. The Windows shell does not glob (i.e., replace arguments containing wildcard markers with the list of files that match the wildcards). Whereas on Unix you can say system("someprog php*.php"), on Windows you must build the list of filenames yourself using opendir() and readdir().

Accessing Platform-Specific Extensions

There are currently well over 80 extensions for PHP covering a wide range of services and functionality. Only about half of these are available for both Windows and Unix platforms. Only a handful of extensions, such as the COM, .NET, and IIS extensions, are specific to Windows. If an extension you use in your scripts is not currently available under Windows, you need to either port that extension or convert your scripts to use an extension that is available under Windows.

In some cases, some functions are not available under Windows even though the module as a whole is available.

Windows PHP does not support signal handling, forking, or multithreaded scripts. A Unix PHP script that uses these features cannot be ported to Windows. Instead, you should rewrite the script to not depend on those features.

Interfacing with COM

COM allows you to control other Windows applications. You can send file data to Excel, have it draw a graph, and export the graph as a GIF image. You could also use Word to format the information you receive from a form and then print an invoice as a record. After a brief introduction to COM terminology, this section shows you how to interact with both Word and Excel.

Background

COM is a remote procedure call (RPC) mechanism with a few object-oriented features. It provides a way for the calling program (the controller) to talk to another program (the COM server, or object), regardless of where it resides. If the underlying code is local to the same machine, the technology is COM; if it’s remote, it’s Distributed COM (DCOM). If the underlying code is a dynamic link library (DLL), and the code is loaded into the same process space, the COM server is referred to as an in-process, or inproc, server. If the code is a complete application that runs in its own process space, it’s known as an out-of-process server, or local server application.

Object Linking and Embedding (OLE) is the overall marketing term for Microsoft’s early technology that allowed one object to embed another object. For instance, you could embed an Excel spreadsheet in a Word document. Developed during the days of Windows 3.1, OLE 1.0 was limited because it used a technology known as Dynamic Data Exchange (DDE) to communicate between programs. DDE wasn’t very powerful, and if you wanted to edit an Excel spreadsheet embedded in a Word file, Excel had to be open and running.

OLE 2.0 replaced DDE with COM as the underlying communication method. Using OLE 2.0, you can now paste an Excel spreadsheet right into a Word document and edit the Excel data inline. Using OLE 2.0, the controller can pass complex messages to the COM server. For our examples, the controller will be our PHP script, and the COM server will be one of the typical MS Office applications. In the following sections, we will provide some tools for approaching this type of integration.

To whet your appetite and show you how powerful COM can be, Example 18-1 shows how you would start Word and add “Hello World” to the initially empty document.

Example 18-1. Creating a Word file in PHP (word_com_sample.php)
// starting word
$word = new COM("word.application") or die("Unable to start Word app");
echo "Found and Loaded Word, version {$word->Version}
";

//open an empty document
$word->Documents->add();

//do some weird stuff
$word->Selection->typeText("Hello World");
$word->Documents[1]->saveAs("c:/php_com_test.doc");

//closing word
$word->quit();

//free the object
$word = null;

echo "all done!";

This code file will have to be executed from the command line in order to work correctly, as shown in Figure 18-1. Once you see the output string of all done!, you can look for the file in the Save As folder and open it with Word to see what it looks like.

Calling the Word sample in the command window
Figure 18-1. Calling the Word sample in the command window

The actual Word file should look something like Figure 18-2.

The Word file as created by PHP
Figure 18-2. The Word file as created by PHP

PHP Functions

PHP provides an interface into COM through a small set of function calls. Most of these are low-level functions that require detailed knowledge of COM that is beyond the scope of this chapter. An object of the COM class represents a connection to a COM server:

$word = new COM("word.application") or die("Unable to start Word app");

For most OLE automation, the most difficult task is converting a Visual Basic method call to something similar in PHP. For instance, this is VBScript to insert text into a Word document:

Selection.TypeText Text := "This is a test"

The same line in PHP is:

$word->Selection->typetext("This is a test");

API Specifications

To determine object hierarchy and parameters for a product such as Word, you might visit the Microsoft developer site and search for the specification for the Word object that interests you. Another alternative is to use both Microsoft’s online VB scripting help and Word’s supported macro language. Using these together will help you understand the order of parameters, as well as the desired values for a given task.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.81.240