Useful php at the command line

The ubuntu command line php uses a special cli build of php by default which is a pain if you want to use it to test or play with php scripts that would normally work on your apache webserver.

The php.ini files used by apache and by the cli build differ and this means that there is no guarantee that the php code will work in both cases.

To align the two, the php.ini loaded files must be similar.

The php command accepts the ini file as a parameter and this feature can be used to make your php at the command line behave the same way as your php called in apache… but not if additional ini files get parsed. Unfortunately that is usually the case.

So here is a sledgehammer solution:

check your command line ini file setup:

~ $ php --ini
Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/pdo.ini

Now check your apache ini file setup (use phpinfo.php in a browser window for this). You need to extract the "loaded configuration file" and the "Scan this dir for additional ini files" entries. In my particular case these were:


Loaded configuration file /usr/local/zend/etc/php.ini
Scan this dir for additional .ini files /usr/local/zend/etc/conf.d

Then as root we'll link things up the way we want it:

~ $ sudo -i
~ # cd /etc/php5/cli
/etc/php5/cli # ls -l
total 72
lrwxrwxrwx 1 root root     9 2010-01-14 09:18 conf.d -> ../conf.d
-rw-r--r-- 1 root root 67457 2010-05-14 06:15 php.ini
/etc/php5/cli # mv conf.d conf.d.bak
/etc/php5/cli # mv php.ini php.ini.bak 
/etc/php5/cli # ln -s /usr/local/zend/etc/conf.d conf.d
/etc/php5/cli # ln -s /usr/local/zend/etc/php.ini php.ini
/etc/php5/cli # ls -l
total 72
lrwxrwxrwx 1 root root    26 2012-06-04 15:06 conf.d -> /usr/local/zend/etc/conf.d
lrwxrwxrwx 1 root root     9 2010-01-14 09:18 conf.d.bak -> ../conf.d
lrwxrwxrwx 1 root root    27 2012-06-04 15:07 php.ini -> /usr/local/zend/etc/php.ini
-rw-r--r-- 1 root root 67457 2010-05-14 06:15 php.ini.bak

Test the result with "php –ini" at the command line. You should see the apache (or zend) php.ini files all loaded and parsed appropriately.

Now when you invoke php at the command line, you get exactly the same php inclusions and behavioural settings you have in apache. That makes the command line version very handy for debugging and development of web applications.


Comments

There are currently no comments

New Comment

required

required (not published)

optional

Australia: 07 3103 2894

International: +61 410 545 357