How to execute PHP code using command line?
PHP Installation for Windows Users
Follow the steps to install PHP on the Windows operating system.
Step 1:
First, we have to download PHP from its official website. We have to download the .zip file from the respective section depending upon our system architecture(x86 or x64).
Step 2:
Extract the .zip file to your preferred location. It is recommended to choose the Boot Drive(C Drive) inside a folder named php (ie. C:\php).
Step 3:
- Access System Properties: Right-click on the “My Computer” or “This PC” icon, select “Properties” from the context menu, then click on “Advanced system settings.”
- Open Environment Variables: In the System Properties window, click on the “Environment Variables” button.
- Edit the PATH Variable: In the “System Variables” section, find the “PATH” variable, select it, and click “Edit.” If it doesn’t exist, click “New” to create it.
- Add PHP Path and Save: In the “Edit System Variable” window, add the path to your PHP folder (e.g., C:\php). Click “OK” to save, and close all remaining windows by clicking “OK.”
PHP Installation for Linux Users
Linux users can install php using the following command.
apt-get install php5-common libapache2-mod-php5 php5-cli
It will install php with apache server.
PHP Installation for Mac Users
Mac users can install php using the following command.
curl -s https://php-osx.liip.ch/install.sh | bash -s 7.3
It will install php in your system.
After installation of PHP, we are ready to run PHP code through command line. You just follow the steps to run PHP program using command line.
- Open terminal or command line window.
- Goto the specified folder or directory where php files are present.
Then we can run php code using the following command:
php file_name.php
We can also start server for testing the php code using the command line by the following command:
php -S localhost:port -t your_folder/
Note: While using the PHP built-in server, the name of the PHP file inside the root folder must be index.php, and all other PHP files can be hyperlinked through the main index page.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.