Sponsored by

  • Intel
  • HP

Web designHow to

How to use the PHP command line

PHP command line

PHP is used by the biggest sites on the net. It also has a powerful command-line version, allowing you to use PHP outside of the scope of a web server. Lorna Jane Mitchell shows us how to get started with the PHP command line.

  • Knowledge needed: Basic PHP
  • Requires: PHP
  • Project Time: About 10 minutes

Using PHP from the command line allows us to use our PHP skills in a whole new world. You can run individual PHP scripts and also run PHP ad-hoc, as you type it. There are tools to check the version and configuration of PHP, and get information about any of the functions, extensions and so on – perfect for being on a plane trying to remember if it's needle or haystack that comes first! Let's take a look at what we can do with this tool.

  • Read all our web design articles here

PHP version and configuration

Here's a good place to start: find the version of PHP that you're running by using php with -v:

      php -v
    ­PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch (cli) (built: May  2 2011 23:18:30)
    Copyright (c) 1997-2009 The PHP Group
    Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

You can see that I'm running PHP 5.3.5 – and there's information there about the specific build (this machine has the default version from Ubuntu's repositories, which includes Suhosin).  This is really handy for a quick check of what is available.

Other great switches for finding out about the current setup, are -m and -i (although both give quite a lot of output so I won't include examples here). The -m gives a full list of the available modules, which is great for checking if you have a particular extension available. The -i option gives information about the configuration, and lots of it. It's similar to the output of phpinfo(), which you might use on a web page to check your setup.

Before we move on, be aware of another favourite: php --ini which shows which ini files have been loaded and can help track down where settings are coming from.

PHP command line

Running PHP from the command line

The simplest way to use PHP's command line is to run a existing PHP script from it. There are a few things that are different, for example the $_SERVER variable holds some different options, appropriate to the platform, but otherwise everything works as you would expect.  Take this simple example:

    <?php
    echo "Hello world!\n";

We use the -f switch to pass a file name into PHP:

    $ php -f hello-world.php
    Hello world!

I use the -f switch a lot for all kinds of things where I really don't need a web browser. I write about PHP a lot, and I also teach it pretty regularly. When I'm developing examples to show off a particular language feature or technique, that typically all happens from the command line.  For jobs that perform monthly tasks, or clean up tables with old data in, I write PHP scripts and fire them off with cron. Quite a few PHP frameworks can also stand to be bootstrapped from the command line, which works really well.

You can also run-as-you-type PHP, which is really useful for checking little snippets. First up, look at this trivial example using -r, allowing us to put in PHP code and immediately run it:

$ php -r '
>
> $a = range(0,2);
> foreach($a as $b) {
>   echo "entry: $b\n";
> }
> '                                                                                                    
entry: 0                                                                                              
entry: 1                                                                                              
entry: 2

For even more immediate feedback, you can run php -a to get a full interactive mode. This will literally evaluate and output each line that you type; you can still use nested structures though and these will be executed when you close the curly brace at the end of them.

Running PHP from the command line might seem strange at first but it performs perfectly well there, allowing you to write scripts in PHP that you might think you needed to learn bash for.  On the command line, PHP's configuration file defaults to having html_errors turned off so the errors appear without the HTML markup you might see in a browser (and even better, Xdebug observes this setting too).

Checking and marking up PHP

PHP can do a simple syntax check without actually running the code, this simply allows it to show those “Unexpected token ...” error messages that you see if you have incorrect syntax in your file. This uses the -l switch:

    $ php -l hello-world.php
    No syntax errors detected in hello-world.php

This is a quick and simple thing to add in to your build scripts, just as an additional check to catch any of these types of errors before they get onto your live platform (obviously we all test our code, but mishaps do happen!).

Another little-known feature is the syntax highlighting feature – this outputs a little bit of HTML markup containing the code, exactly as you see in the PHP manual itself. Here's what happens when I point it at my hello-world.php file:

    $ php -s hello-world.php
    <code><span style="color: #000000">
    <span style="color: #0000BB">&lt;?php<br /><br /></span><span style="color: #007700">echo </span><span style="color: #DD0000">"Hello world!\n"</span><span style="color: #007700">;<br /><br /><br /></span>
    </span>
    </code>

As HTML, we see:

PHP command line

Command-line documentation features

Since PHP 5.1.2, we've had some additional options on which use reflection to inspect functions, classes and extensions from the command line. This is great if you don't have access to the online manual for any reason. For example, we can look up the argument order on str_replace() like this:

    $ php --rf str_replace
    Function [ <internal:standard> function str_replace ] {
     
      - Parameters [4] {
        Parameter #0 [ <required> $search ]
       Parameter #1 [ <required> $replace ]
       Parameter #2 [ <required> $subject ]
       Parameter #3 [ <optional> &$replace_count ]
     }
    }

I can easily see what order the three main parameters should be used in, and there's also an optional argument shown that can capture how many times there was a replacement made.  This documentation is available for functions using --rf, for classes using --rc, for extensions using --re, and you can also get the configuration options for a particular extension by using --ri.

All in all, there's a host of features in command line PHP and I hope this has given you a good idea what's available so that you can use these in the future if you need them.

Lorna is an independent web development consultant, trainer and author based in Leeds, UK. She is a PHP specialist and works with teams to get the most out of their applications, their tools, and their people. Lorna is a regular conference speaker and lead developer at the Joind.in open source project.

Liked this? Read these!

Subscription offer

Log in to Creative Bloq with your preferred social network to comment

OR

Log in with your Creative Bloq account

site stat collection