Log4php is a php port of Log4j, the most popular Java logging framework (see http://jakarta.apache.org/log4j/ for details).



  • Supports configuration through xml and properties file (same structure as log4j).
  • Supports File, RollingFile, DailyFile, Echo, Console, Mail, PEAR::Db, PHP error, Syslog or NT events and Socket appenders.
  • Supports Simple, TTCC, Pattern, Html and Xml Layouts.
  • Supports Nested (NDC) and Mapped (MDC) Diagnostic Contexts.
  • Switchable internal debug.

It can be used inside a class (see below) or inside a main/sub function.


  • PHP >= 4.1.x (to log caller location information PHP >= 3.2.0 is needed)
  • PEAR XML_Parser class (located in PEAR/XML/Parser.php by default) only for log4php version <= 0.3.


First read the original log4j documentation.
Then, read the log4php quick setup guide.
Finally, for further informations, browse the online api documentation.


Here is an example on how to use in your php code (usage.php).
For more examples see tests/ directory in the log4php distribution.
Take also a look at original log4j documentation.

Refer: http://www.vxr.it/log4php/#intro

Using PHP from the command line


Using PHP from the command line

As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It’s worth mentioning that CLI and CGI are different SAPI’s although they do share many of the same behaviors.

The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental and had to be explicitly enabled with –enable-cli when running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimental and the option –enable-cli is on by default. You may use –disable-cli to disable it.

As of PHP 4.3.0, the name, location and existence of the CLI/CGI binaries will differ depending on how PHP is installed on your system. By default when executing make, both the CGI and CLI are built and placed as sapi/cgi/php and sapi/cli/php respectively, in your PHP source directory. You will note that both are named php. What happens during make install depends on your configure line. If a module SAPI is chosen during configure, such as apxs, or the –disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if –with–apxs is in your configure line then the CLI is copied to {PREFIX}/bin/php during make install. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify –disable-cgi in your configure line.

Note: Because both –enable-cli and –enable-cgi are enabled by default, simply having –enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.

The Windows packages between PHP 4.2.0 and PHP 4.2.3 distributed the CLI as php-cli.exe, living in the same folder as the CGI php.exe. Starting with PHP 4.3.0 the Windows package distributes the CLI as php.exe in a separate folder named cli, so cli/php.exe . Starting with PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.

As of PHP 5, a new php-win.exe file is distributed. This is equal to the CLI version, except that php-win doesn’t output anything and thus provides no console (no “dos box” appears on the screen). This behavior is similar to php-gtk. You should configure with –enable-cli-win32.

Note: What SAPI do I have?
From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.

Note: A Unix manual page was added in PHP 4.3.2. You may view this by typing man php in your shell environment.

Remarkable differences of the CLI SAPI compared to other SAPIs:

·         Unlike the CGI SAPI, no headers are written to the output.

Though the CGI SAPI provides a way to suppress HTTP headers, there’s no equivalent switch to enable them in the CLI SAPI.

CLI is started up in quiet mode by default, though the -q and –no-header switches are kept for compatibility so that you can use older CGI scripts.

It does not change the working directory to that of the script. (-C and –no-chdir switches kept for compatibility)

Plain text error messages (no HTML formatting).

·         There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:

Overridden php.ini directives


CLI SAPI default value




It can be quite hard to read the error message in your shell when it’s cluttered with all those meaningless HTML tags, therefore this directive defaults to FALSE.



It is desired that any output coming from print(), echo() and friends is immediately written to the ou

tput and not cached in any buffer. You still can use output buffering if you want to defer or manipulate standard output.


0 (unlimited)

Due to endless possibilities of using PHP in shell environments, the maximum execution time has been set to unlimited. Whereas applications written for the web are often executed very quickly, shell application tend to have a much longer execution time.



Because this setting is TRUE you will always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments) in the CLI SAPI.

As of PHP 4.3.0, the PHP variables $argc and $argv are registered and filled in with the appropriate values when using the CLI SAPI. Prior to this version, the creation of these variables behaved as they do in CGI and MODULE versions which requires the PHP directive register_globals to be on. Regardless of version or register_globals setting, you can always go through either $_SERVER or $HTTP_SERVER_VARS. Example: $_SERVER[‘argv’]

·         Note: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).

·         To ease working in the shell environment, the following constants are defined:

CLI specific Constants




An already opened stream to stdin. This saves opening it with



= fopen(‘php://stdin’, ‘r’);


If you want to read single line from stdin, you can use

$line = trim(fgets(STDIN)); // reads one line from STDIN
fscanf(STDIN, “%dn”, $number); // reads number from STDIN


An already opened stream to stdout. This saves opening it with



= fopen(‘php://stdout’, ‘w’);



An already opened stream to stderr. This saves opening it with



= fopen(‘php://stderr’, ‘w’);


·         Given the above, you don’t need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

·         php -r 'fwrite(STDERR, "stderrn");'

·         You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

·         Note: These constants are not available in case of reading PHP script from stdin.

·         The CLI SAPI does not change the current directory to the directory of the executed script!

Example showing the difference to the CGI SAPI:

// Our simple test application named test.php
echo getcwd(), “n”;

When using the CGI version, the output is:

$ pwd
$ php -q another_directory/test.php

This clearly shows that PHP changes its current directory to the one of the executed script.

Using the CLI SAPI yields:

$ pwd
$ php -f another_directory/test.php

This allows greater flexibility when writing shell tools in PHP.

Note: The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.

The list of command line options provided by the PHP binary can be queried anytime by running PHP with the -h switch:

Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] — [args...]
       php [options] -a
  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value ‘bar’
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.
  args…          Arguments passed to script. Use — args when first argument
                   starts with - or script is read from stdin
  –ini            Show configuration file names
  –rf <name>      Show information about function <name>.
  –rc <name>      Show information about class <name>.
  –re <name>      Show information about extension <name>.
  –ri <name>      Show configuration for extension <name>.

The CLI SAPI has three different ways of getting the PHP code you want to execute:

1.      Telling PHP to execute a certain file.

3.  php my_script.php
5.  php -f my_script.php

Both ways (whether using the -f switch or not) execute the file my_script.php. You can choose any file to execute – your PHP scripts do not have to end with the .php extension but can have any name or extension you wish.

If you need to pass arguments to your scripts you need to pass as the first argument when using the -f switch.

8.      Pass the PHP code to execute directly on the command line.

10.php -r 'print_r(get_defined_constants());'

Special care has to be taken in regards of shell variable substitution and quoting usage.

Note: Read the example carefully, there are no beginning or ending tags! The -r switch simply does not need them. Using them will lead to a parser error.

13.  Provide the PHP code to execute via standard input (stdin).

This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:

$ some_application | some_filter | php | sort -u >final_output.txt

You cannot combine any of the three ways to execute code.

Like every shell application, the PHP binary accepts a number of arguments but your PHP script can also receive arguments. The number of arguments which can be passed to your script is not limited by PHP (the shell has a certain size limit in the number of characters which can be passed; usually you won’t hit this limit). The arguments passed to your script are available in the global array $argv. The zero index always contains the script name (which is in case the PHP code is coming from either standard input or from the command line switch -r). The second registered global variable is $argc which contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments you want to pass to your script do not start with the character, there’s nothing special to watch out for. Passing an argument to your script which starts with a will cause trouble because PHP itself thinks it has to handle it. To prevent this, use the argument list separator . After this separator has been parsed by PHP, every argument following it is passed untouched to your script.

# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
# This will pass the ‘-h’ argument to your script and prevent PHP from showing it’s usage
$ php -r ‘var_dump($argv);’ — -h
array(2) {
  string(1) “-”
  string(2) “-h”

However, there’s another way of using PHP for shell scripting. You can write a script where the first line starts with #!/usr/bin/php. Following this you can place normal PHP code included within the PHP starting and end tags. Once you have set the execution attributes of the file appropriately (e.g. chmod +x test) your script can be executed like a normal shell or perl script:

Example #1 Execute PHP script as shell script


Assuming this file is named test in the current directory, we can now do the following:

$ chmod +x test
$ ./test -h -- foo
array(4) {
  string(6) “./test”
  string(2) “-h”
  string(2) “–”
  string(3) “foo”

As you see, in this case no care needs to be taken when passing parameters which start with to your script.

Long options are available since PHP 4.3.3.

Command line options


Long Option




Runs PHP interactively. If you compile PHP with the Readline extension (which is not available on Windows), you’ll have a nice shell, including a completion feature (e.g. you can start typing a variable name, hit the TAB key and PHP completes its name) and a typing history that can be accessed using the arrow keys. The history is saved in the ~/.php_history file.

Note: Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions – e.g. functions have to be defined before called.

Note: Autoloading is not available if using PHP in CLI interactive mode.



This option can either specify a directory where to look for php.ini or specify a custom INI file (which does not need to be named php.ini), e.g.:

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

If you don’t specify this option, file is searched in default locations.



Ignore php.ini at all. This switch is available since PHP 4.3.0.



This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is:

-d configuration_directive[=value]

Examples (lines are wrapped for layout reasons):

# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"
# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""
# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"



Activate the extended information mode, to be used by a debugger/profiler.



Parses and executes the given filename to the -f option. This switch is optional and can be left out. Only providing the filename to execute is sufficient.

Note: To pass arguments to scripts the first argument needs to be , otherwise PHP will interperate them as PHP options.

-h and -?

–help and –usage

With this option, you can get information about the actual list of command line options and some one line descriptions about what they do.



This command line option calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore quite huge.



This option provides a convenient way to only perform a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to 255.

This option won’t find fatal errors (like undefined functions). Use -f if you would like to test for fatal errors too.

Note: This option does not work together with the -r option.



Using this option, PHP prints out the built in (and loaded) PHP and Zend modules:

$ php -m
[PHP Modules]
[Zend Modules]



This option allows execution of PHP right from within the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parser error if present.

Note: Care has to be taken when using this form of PHP to not collide with command line variable substitution done by the shell.

Example showing a parser error

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='

The problem here is that the sh/bash performs variable substitution even when using double quotes . Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:

$ php -r " = get_defined_constants();"

The correct way would be to use single quotes . Variables in single-quoted strings are not expanded by sh/bash.

$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {


If you are using a shell different from sh/bash, you might experience further issues. Feel free to open a bug report at » http://bugs.php.net/. One can still easily run into troubles when trying to get shell variables into the code or using backslashes for escaping. You’ve been warned.

Note: -r is available in the CLI SAPI and not in the CGI SAPI.

Note: This option is meant for a very basic stuff. Thus some configuration directives (e.g. auto_prepend_file and auto_append_file) are ignored in this mode.



PHP code to execute before processing stdin. Added in PHP 5.



PHP code to execute for every input line. Added in PHP 5.

There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number.



PHP file to execute for every input line. Added in PHP 5.



PHP code to execute after processing the input. Added in PHP 5.

Example #2 Using the -B, -R and -E options to count the number of lines of a project.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $ln";'
Total Lines: 37328


–syntax-highlight and –syntax-highlight

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and produces a HTML highlighted version of it and writes it to standard output. Note that all it does it to generate a block of <code> […] </code> HTML tags, no HTML headers.

Note: This option does not work together with the -r option.



Writes the PHP, PHP SAPI, and Zend version to standard output, e.g.

$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies



Display source with stripped comments and whitespace.

Note: This option does not work together with the -r option.



Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually specified /etc/ld.so.conf on Linux systems). Passing a filename with an absolute path information will not use the systems library search path. A relative filename with a directory information will tell PHP only to try to load the extension relative to the current directory.


Shows configuration file names and scanned directories. Available as of PHP 5.2.3.

Example #3 –ini example

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)



Shows information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #4 basic –rf usage

$ php --rf var_dump
Function [ <internal> public function var_dump ] {
  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]



Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #5 –rc example

$ php --rc Directory
Class [ <internal:standard> class Directory ] {
  - Constants [0] {
  - Static properties [0] {
  - Static methods [0] {
  - Properties [0] {
  - Methods [3] {
    Method [ <internal> public method close ] {
    Method [ <internal> public method rewind ] {
    Method [ <internal> public method read ] {



Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #6 –re example

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {
  - Functions {
    Function [ <internal> function json_encode ] {
    Function [ <internal> function json_decode ] {



Shows the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information are available using “main” as extension name.

Example #7 –ri example

$ php --ri date
date/time support => enabled
"Olson" Timezone Database Version => 2007.5
Timezone Database => internal
Default timezone => Europe/Oslo
Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.22482 => 59.22482
date.default_longitude => 11.018084 => 11.018084
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won’t hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.

Example #8 Script intended to be run from command line (script.php)


if ($argc != 2 || in_array($argv[1], array(‘–help’, ‘-help’, ‘-h’, ‘-?’))) {

This is a command line PHP script with one option.

<?php echo $argv[0]; ?> <option>

<option> can be some word you would like
to print out. With the –help, -help, -h,
or -? options, you can get this help.

} else {
echo $argv[1];

In the script above, we used the special first line to indicate that this file should be run by PHP. We work with a CLI version here, so there will be no HTTP header printouts. There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

In the program above we checked if there are less or more than one arguments. Also if the argument was –help, -help, -h or -?, we printed out the help message, printing the script name dynamically. If we received some other argument we echoed that out.

If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:

Example #9 Batch file to run a command line PHP script (script.bat)

@C:phpphp.exe script.php %1 %2 %3 %4

Assuming you named the above program script.php, and you have your CLI php.exe in C:phpphp.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.


How to optimize your PHP installation to handle large file uploads.

Though PHP presents a very versatile and user friendly interface for handling file uploads, the default installation is not geared for working with files in excess of 2 Mega Bytes. This article will help you configure your PHP engine for handling such large file transfers.

The php.ini File

<!– li { margin-top: 5px; } –>





Special Note:

You could be wasting bandwidth, If your file upload page is nothing more than an HTML form.

Most browsers just ignore the MAX_FILE_SIZE hidden field and size limits are checked only after the data has been sent over the wire.

Our applet saves your bandwidth by imposing client side restrictions.





All the configuration settings for your installation are contained in the php.ini file. Sometimes these setting might be overridden by directives in apache .htaccess files or even with in the scripts themselves. However you cannot over ride some of the settings that effect file uploads with .htaccess directives in this way. So let’s just concentrate on the ini file. If you do not have access to your PHP configuration file you can use the applet in resumable mode

You can call the phpinfo() function to find the location of your php.ini file, it will also tell you the current values for the following settings that we need to modify

  • file_uploads
  • upload_max_filesize
  • max_input_time
  • memory_limit
  • max_execution_time
  • post_max_size

The first one is fairly obvious if you set this off, uploading is disabled for your installation. We will cover the rest of the configuration settings in detail below.

upload_max_filesize and post_max_size

Files are usually POSTed to the webserver in a format known as ‘multipart/form-data’. The post_max_size sets the upper limit on the amount of data that a script can accept in this manner. Ideally this value should be larger than the value that you set for upload_max_filesize.

It’s important to realize that upload_max_filesize is the sum of the sizes of all the files that you are uploading. post_max_size is the upload_max_filesize plus the sum of the lengths of all the other fields in the form plus any mime headers that the encoder might include. Since these fields are typically small you can often approximate the upload max size to the post max size.

According to the PHP documentation you can set a MAX_UPLOAD_LIMIT in your HTML form to suggest a limit to the browser. Our understanding is that browsers totally ignore this directive and the only solution that can impose such a client side restriction is our own Rad Upload Applet


When the PHP engine is handling an incoming POST it needs to keep some of the incoming data in memory. This directive has any effect only if you have used the –enable-memory-limit option at configuration time. Setting too high a value can be very dangerous because if several uploads are being handled concurrently all available memory will be used up and other unrelated scripts that consume a lot of memory might effect the whole server as well.

max_execution_time and max_input_time

These settings define the maximum life time of the script and the time that the script should spend in accepting input. If several mega bytes of data are being transfered max_input_time should be reasonably high. You can override the setting in the ini file for max_input_time by calling the set_time_limit() function in your scripts.

Additonal Comments

Apache Settings

The apache webserver has a LimitRequestBody configuration directive that restricts the size of all POST data regardless of the web scripting language in use. Some RPM installations sets limit request body to 512Kb. You will need to change this to a larger value or remove the entry altogether.

Other Options

If you expect to handle a large number of concurrent file transfers on your website consider using a perl or java server side component. PHP happens to be our favourite web programming language as well but perl and Java are just slightly ahead when it comes to file upload.

Most installations of perl as an apache module can accept in excess of 32 megabytes out of the box. Compare this against the 2MB default for PHP. The downside is that perl coding takes just a bit more effort than PHP but it’s worth it. You can try our sample scripts to get started.

PHP – Ubuntu 9.04 + PHP5 + GD2

It all started when I decided to optimize image slicing algorithm for a new feature on UMapper – and since GD is quite RAM-intensive, I needed to check actual memory consumption, and the obvious choice to do so was PHP’s memory_get_usage() function. However, it failed to produce accurate results – it seemed like images loaded into memory weren’t accounted by the function (RAM was still used :) ).
As it turned out, whoever prepared official php5-gd package, compiles against original GD, and not using PHP5 bundled version of the library. I actually wasn’t aware about the fork, but here is explanation from GD Official Site:

The PHP version of gd offers features similar to and sometimes in addition to those included in the latest version of gd found here as well as many bug fixes not present in the latest GD release. If you are working with PHP, using the built-in gd of PHP 4.3.0 or better is recommended.

We are working to merge the changes done in the PHP GD in the normal GD library.

Well, I was pretty sure that unexpected behavior was caused by using original GD library instead of bundled one. So I decided to remove php5-gd package, recompile php5 from sources, and install updated GD package – which is exactly what gets bundled with PHP5 on other distributions.

Google is my friend, so here is a walkthrough:

# Install build tools, debian helpers and fakeroot
apt-get install build-essential debhelper fakeroot
# Get PHP source (it should go into /usr/src)
cd /usr/src
apt-get source php5
# Install all packages required to build PHP5
apt-get build-dep php5

#Now what we need is to update compile options,
# so we need to edit debian/rules file:
cd php5-5.2.6.dfsg.1
vim debian/rules
# locate the line having “–with-gd=shared,/usr –enable-gd-native-ttf \”
# replace with “–with-gd=shared –enable-gd-native-ttf \”
# that’s remove reference to /usr so that bundled library is used

# compile (drink some coffee, walk you dog, see the latest House episode)
dpkg-buildpackage -rfakeroot

# install the new php5-gd package
cd ..
dpkg -i php5-gd_5.2.6.dfsg.1-3ubuntu4.2_i386.deb

# finally restart apache
/etc/init.d/apache2 restart

That’s it – you should be able to see «bundled» near the GD version in the phpinfo() output. Well, that’s not the only gain – it solves problem with memory_get_usage() as well :)

Now, once I had memory_get_usage() working correctly, back to optimization..