Get DevWP - WordPress Development Theme

PHP CLI – Built In Web Server

Subscribe To PixemWeb on YouTube

PHP is most often used with a Web Server like Apache or NGinx and the output is typically viewed in a web browser. But you can also use PHP in the Command Line Interface aka CLI. This is a great way to work through code without having to launch web server from another program.

In this tutorial I show you how to use PHP in the Command Line Interface and how to utilize the built in web server provided by PHP.

In order to use PHP in the Command Line you will need to make sure it’s installed on your system and recognized by your path/env. If you are already using a packaged program like MAMP or XAMPP, you already have PHP.

PHP Built-in Web Server

Note: the PHP Built-in web server is only meant to be used in a development environment.

In your terminal application, you would use the below command which starts with php followed by the -S flag and then your host/ip and port number.


php -S <host/ip>:<port>

Create a php file and name it either index.php if it’s going to be the root file, or give it a file name of your choosing.


<?php
echo "Hello World! I'm coming from the built-in PHP web server";
?>

Then in your terminal application, run the following command which will start a local web server.


php -S localhost:8080

Then open up a browser window and visit either localhost:8080 if you used index.php as the file name or if you used a different file name like say example.php: localhost:8080/example.php


PHP CLI Explained

The PHP built-in web server definitely comes in handy when you don’t want to run another application and just want to use the server that comes with PHP. But you can actually simplify your development process even further by running PHP from the command line and outputting the results in the terminal instead of a web browser.

There are 4 ways to run PHP Code in the CLI:

1. Using the Standard Input with the php command without using any arguments while piping your php code.


echo '<?php echo "Hello world!";?>' | php


2. Using a filename as an argument by running the php command with the file you want to use.


php hello-world.php


3. Using your code as the argument with the -r flag, followed by the code you want to execute.


php -r 'echo "Hello world!";'


4. Using an Interactive shell with the -a flag. First type out the snippet below and press return.


php -a

The terminal output should be: Interactive Mode or Interactive Mode Enabled.

Then you should see php >.

Then enter your code as demonstrated below.


echo "Hello World!";

The output should be Hello World!


Using PHP in the Command Line or the Built-in Web Server is a great way to work with your code. You can always learn more about what’s possible in the PHP CLI by using the command below.


php -h

This will list out all the command line options provided by PHP.



View Our Themes

Let's Connect