When it comes to trying out a snippet of PHP, the process can often be time consuming and tedious. Loading up your editor, saving a new file in your http docs folder, firing up a webserver, running some tests and then clearing the files off – it’s generally more trouble than its worth. Thankfully, PHP provides the interactive shell, allowing you to test out PHP interactively with immediate feedback. Here’s how to take advantage of this mature feature of PHP.
Make sure the folder with your PHP interpreter (where php.exe or the compiled php binary is stored) is in your system’s PATH. Here are some instructions for linux and windows. You can test that PHP is in your path by firing up a command prompt / console window and running “php -v”. You should see your PHP version.
Provided you have a reasonably recent version of PHP (any version of PHP 5 is sufficient), you’re now all set to use PHP interactive mode! Open up a command prompt / console window and run “php -a”. You will see a message saying “Interactive mode enabled.” Next, type out a PHP open tag –
There are a few quirks to remember when working with interactive mode.
First, avoid jumping in and out of code blocks. When you close a PHP block, type out some text and open another PHP block, PHP will output everything between the last close and open tag.
Your statements can span multiple lines – but remember to put in the closing semicolon. This might be obvious in an IDE, but it’s a common mistake in a simple terminal.
If something isn’t working quite right, debug your variables with echo calls – that’s what the interactive shell is for.
Watch your current directory. You may find the __FILE__ magic constant useful. If you want to get the current directory, it’s the ‘dirname’ element of pathinfo(__FILE__). Generally, this will be the path under which you called php -a, but it can be slightly erratic. If you want to include other PHP files from the interactive shell (which can definitely be done, and is encouraged to test and play around with libraries), you may be safest using absolute paths.
Also, remember that you do not need to type in your PHP code to test it using the PHP binary. While this is outside the area of the interactive shell, calling “php filename.php” will execute filename.php as a standard PHP script, which may prove useful for cron jobs / scheduled tasks or just plain testing.