Sometime it is relevant to run php script in native command line or it is also required PHP editor for check the syntaxes and other activities. For example, Visual Studio Code's PHP IntelliSense extension needed the PHP, for that we need to add the PHP executable path on settings.json file (php.executablePath.
Now a days nobody installing the PHP on native machines, so in this case we can use PHP docker container for make a PHP executable command.
Following steps based on the Macbook but this solution will work in Linux machine.
Steps
- 1. Install Docker your machine if it is not there.
- 2. Create specific folder for custom command in my case I created a folder like /Users/harivenu/CustomCommand/
- 3. Create file and name it as php then add below lines. NOTE: For creating a file you can use either command line Vim or use any text editors
#!/bin/sh
docker run \
--network=host \
--rm \
-e HOME="$HOME" \
-u $(id -u):$(id -g) \
-v "$HOME":"$HOME" \
-w "$PWD" \
php:8.2-alpine \
php "$@"
exit $?
- 4. Add executable permission
$ chmod +x /Users/harivenu/CustomCommand/php
- 5. Add the folder path to $PATH variable, for Mac OS you can open the file /etc/paths on your command line vi editor then add the path in the end of the file like below.
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/Users/harivenu/CustomCommand
For Linux you can update $PATH variable by using .bashrc file
export PATH="$PATH:/home/harivenu/CustomCommand"
- 6. Open a new terminal then check PHP command is working or not. Expected output added below
$ php -v
PHP 8.2.3 (cli) (built: Feb 14 2023 20:48:45) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.3, Copyright (c) Zend Technologies
This is very reliable method and flexible to change the PHP version based on the availability of the PHP container in Docker hub.