How can I force PHP Version for Command Line?

2019-04-04 17:03发布

问题:

I am hosted with 1and1.com, and I have setup my files to be parsed with php5 using .htaccess.

But that only works in apache, and not in command line, which defaults to the server default php4.

So currently I can not setup cron jobs to run my code as php5. Any ideas?

回答1:

If both are installed, all you need to do is run the script using the relevant PHP binary.

So for example:

 // Runs using the PHP binary located at /usr/bin/php
 * * * * * root /usr/bin/php -n "/path/to/script.php"

or

 // Runs using the PHP binary located at /var/php5
 * * * * * root /var/php5 -n "/path/to/script.php"

All you need to know is the full file system path of the PHP CLI binaries, and call the relevant one to run your code.



回答2:

In accordance to https://community.1and1.com/using-php-composer-at-1and1/, create .profile in your root projet and add the line :

alias php='/usr/bin/php5.5-cli'

It works for me. Log out and log back in SSH and do :

php -v

Result :

PHP 5.5.32 (cli) (built: Feb 15 2016 16:13:44)



回答3:

If you can execute PHP scripts directly in the shell like:

$ script.php

you can specify the binary that will execute the script in it's first line:

#!/usr/bin/php
<?php

That line is called shebang. The line might differ on your system, you need to know the full file system path of the PHP CLI binary you want to use for that script.

If you execute that file in the shell, the specified binary will be used. Same for cron.

If you execute that file via your webserver, PHP will drop that line silently.

See as well: Features: Using PHP from the command line



回答4:

there must be two PHP directories and one of them should be the default one. try to find out php5's path from the root of your server and use full path at your cron job.



回答5:

This is another approach to force PHP from Command Line on 1and1.

Log in with ssh on your server and create a new file called .profile in there you will write the following line alias php='/usr/local/bin/php5' Log back in with ssh and check php version with php -v you should see the version is now 5.



回答6:

I finally got this working. The problem was a few-fold.

First, the PHP being used was in /etc/bin instead of the MAMP version. I was able to change this and use the MAMP version instead.

Second, to use php via the CLI you have to make sure to use the FULL path to php and not just php itself. I.e. use /MAMP/bin/php/php5.3.x/php in your exec() call. This is now working for me.

You can check out my GIST here...https://gist.github.com/1861487