Execute PHP Code & Scripts / Files in Bash / SSH & Cron

Execute PHP Code in Bash/SSH and Cron

To execute PHP code via shell, type the following code after you SSH into your server:

php -r 'echo "Hello World";'

The above code simply outputs Hello World, but feel free to use your own PHP code between the apostrophes in the above example.

Execute PHP Script/File in Bash/SSH and Cron

To execute a PHP script/file via shell, you must first run the following command to get the PHP directory:

which php

The output will be what you want. It should be something like this:

/usr/local/bin/php

You would then run a PHP file by typing in the following:

/usr/local/bin/php /home/username/public_html/filetoexecute.php

If the output of the which php command did not give you the correct directory, then you need to know what version of PHP your web server is using. To find out, type the following code after you SSH into your server:

php -v

The above code will tell you what version of PHP you are using on your web server. If you are using PHP 5.4, you would execute a PHP file by typing in the following via SSH:

/opt/php54/bin/php /home/username/public_html/filetoexecute.php

If you have a different version of PHP than 5.4, you will use a slightly different command. Simply substitute the 4 with the relevant number.

The following are locations for different PHP versions:
PHP 5.2: /opt/php52/bin/php
PHP 5.3: /opt/php53/bin/php
PHP 5.4: /opt/php54/bin/php
PHP 5.5: /opt/php55/bin/php
PHP 5.6: /opt/php56/bin/php

If that command is not working for you, try looking for the correct location using the following command via SSH:

whereis php