How Can I Execute PHP Code From the Command Line

As a software developer, you may have heard of running PHP scripts from the command line interface (CLI).

The CLI is a powerful tool that allows you to execute PHP code without the need for a web server.

This can be especially useful when you want to automate tasks, test your code, or execute scripts that don’t require a web browser.

In this tutorial, we’ll cover everything you need to know to run PHP code from the command line.


Prerequisites

Before we dive into the details, there are a few things you’ll need to make sure you have:

  • A computer running a operating system that supports the PHP CLI (such as Windows, macOS, or Linux)
  • PHP installed and configured on your computer

How to Check if PHP is Installed on Your Computer

The easiest way to check if PHP is installed on your computer is to open the command prompt (or terminal on macOS/Linux) and type the following command:

php -v

If PHP is installed, you should see the version number displayed in the output.

If you receive an error message saying “php is not recognized as an internal or external command,” it means that PHP is not installed on your computer or it’s not added to your PATH environment variable.

In this case, you’ll need to install PHP before you can run it from the command line.

How to Write and Run a PHP Script from the Command Line

Now that you have PHP installed, you can write and run a simple PHP script from the command line.

Here’s how:

  1. Open a text editor such as Notepad++ or Sublime Text
  2. Write the following code in your text editor:
<?php
echo "Hello, World!";
  1. Save the file with a .php extension, for example, “hello.php”
  2. Open the command prompt (or terminal on macOS/Linux)
  3. Navigate to the directory where you saved the “hello.php” file
  4. Type the following command:
php hello.php
  1. Press enter

You should see the following output:

Hello, World!

And that’s it! You’ve just run your first PHP script from the command line.


Conclusion

Running PHP from the command line is a powerful tool that can help you automate tasks, test your code, or execute scripts that don’t require a web browser.

With the steps outlined in this tutorial, you should have no problem getting started with PHP from the command line.