TL;DR: I’ve been writing PHP command-line scripts to help automate mundane tasks. As these tasks are growing in complexity or turning more into applications that interface with third-party APIs, I’m documenting the things I find important that others may also find helpful.
There are three things necessary to get a basic script up and running on your local machine (assuming you already have PHP installed):
- Know the path to the PHP binary,
- Make sure your script references said binary,
- And make the script executable.
Setting Up the Basic Script
First, find the location to your PHP installation binary. For some, this will be located as something like
/usr/local/bin/php. For others, if you use something such as Homebrew, it may be something else .
In the latter case, it may look like this:
You can determine which by running
$ which php at the command-line. Remember this path as it’s necessary in the next step.
Next, open your script (or
touch the file then open it) and make sure the top of the file contains the path to the PHP binary prefixed by a shebang. If you’re using the default installation of PHP, it will look like this:
In my case, though, it looks like this:
After that, you can enter in the basics of your script. To get something started, try entering something like this:
#!/usr/local/bin/php <?php echo "Script executed!"
Finally, in your terminal, execute the following command:
$ chmod +x script.php (assuming that your script is named
script.php). This changes the permissions on the file so that it can be executed. From the command line, you should then be able to run
$ ./script.php and see Script executed! as the following output.
And this will appear directly below where you’ve entered the command.
Finally, as you likely well know, it’s possible to enter command-line arguments to work with them as a type of interface to the script or application. And in a future post in the series, I’ll share more about that.
Update 25 January 2021: A good conversation with a previous colleague and fellow engineer took place on Twitter on recognizing the importance of your
PATH when following the steps above.
In short, make sure that the order of your PHP installations are in priority in your shell’s
PATH to make sure you get the version you expect.