Reading from standard input and writing to standard output or standard error using PHP

One of the most common command line tricks in Linux is to chain multiple commands using the pipe symbol i.e. you feed the output of one command as the input of another. This is called standard input and standard output redirection. PHP is usually used to program for the web but it can also be used as a shell scripting language to automate tasks and like any good shell scripting language it is possible to read from standard input and write to standard output using PHP.

Continue reading

Converting a string to a number consistently using PHP

Say you want to convert strings to numbers such that a string will always convert to the same number. So for example the string
“red” will always convert to 2 or the string “blue” will always convert to 1. You don’t know which strings you are going to get and the exact number they convert to doesn’t matter just that it always converts to the same number. The reason you want to do this is to pick a value from an array based on that string-converted-to-a-number i.e. you want to use the string-converted-to-a-number as the array’s index or key. How do you do that conversion using PHP?
Continue reading

Upgrade to PHP 5.3 on CentOS 5

By default CentOS 5 comes with PHP version 5.1. This is an ancient version of PHP and incompatible with modern Content Management Systems (CMS). This point is driven home with the recent release of WordPress 3.2 that requires a minimum of PHP 5.2.4. Because WordPress is such a popular CMS and CentOS such a popular web server operating system it seems like a good time to write about updating PHP to version 5.3.3 on CentOS 5.

Continue reading

Reduce CPU load with Alternative PHP Cache

alternative php cachePHP is by far the most popular scripting language for dynamic web pages but it is not the most efficient language. Each time a PHP page is accessed it has to be:

  • Parsed by the interpreter
  • Converted into intermediary format called opcode
  • Converted into machine code for your server’s CPU to execute it

If the same script is accessed 100 times these steps are repeated a 100 times. To avoid this repetition and waste of server resources you can use the Alternative PHP Cache or APC.

APC is a PECL extension that caches frequently accessed PHP files code in opcode format for faster execution thereby reducing CPU load on your web server. In this guide I write about how to install and configure APC.

Continue reading