Running PHP scripts

You can execute your scripts in one of two ways: through a web server where the output is a web browser, or through the command line where the output is the command line itself. Of the two, the former is much more popular, but the latter is steadily growing in popularity.

We cover both methods of script execution in this book, with the bias towards web server usage. Most scripts will work smoothly in either environment, with the exception of scripts covered in the chapter "Alternative PHP uses", which require specific environments. You're encouraged to try using both when reading this book - it will give you more familiarity with how PHP works, and will also give you good experience using the CLI SAPI to debug your scripts.

The primary difference between outputting text to the command line and to a web browser is the format of new lines - through the CLI you need to use \n for a new line, whereas for web browsers you need to use the HTML line break, <br />. If you want to take a script designed for CLI and make it work through the web, swap \n for <br />, and vice versa for converting web scripts to command line scripts.

Running scripts through your web server is as simple as putting the PHP script into your web server's public directory, then navigating to the appropriate URL with your browser. Hopefully you will already have followed the official PHP installation instructions for your platform!

Running scripts through the command line is done using the CLI SAPI, which, if you are using Windows, can be found in the directory of your PHP installation, which is probably c:\Program Files\PHP. If you are using Unix, you may find the CLI SAPI is available in a special package called something like php5-cli or just php-cli.

Later on we'll look at more detailed information on how using the CLI SAPI is different from normal PHP scripting, so don't rush off and try it out just yet!

If you are not sure about whether PHP is set up on your machine correctly, the best way forward is to run the following script:

<?php
    phpinfo();
?>

That calls a special function, phpinfo(), which outputs all the information PHP currently has - how it was configured, what server it is running on, what modules are available, and more. It is very handy to keep around when you are developing, as it will answer most questions you have about configuration.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: How PHP is written >>

Previous chapter: PEAR

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.