Using bash shell from within PHP

2019-02-26 11:04发布

In my terminal window (using Max OS X) my shell is bash. However when I run a command in PHP via shell_exec or backtick operators I see that PHP is using the Bourne Shell (sh). Here's an example of what I'm seeing:

From within my terminal window:

$ echo $0
- bash

Also if I call php as follows:

$ php -r "echo shell_exec('echo $0');"
-bash

However, if I create a script called test.php with the following:

<?php echo shell_exec('echo $0'); ?>

And then run test php I get the following:

$ php test.php
sh

I'm wanting to use the bash shell when calling shell_exec - why is it choosing the Bourne shell and can I force it to use bash?

Thanks!

Dan

标签: php bash shell
3条回答
该账号已被封号
2楼-- · 2019-02-26 11:20

Reverse the quotes in your second command:

$ php -r 'echo shell_exec("echo $0");'
sh

With the quotes as you had them in your question, the variable $0 is expanded before the command is sent to php.

If you want to force the use of Bash, you could do something like:

php -r '$cmd="echo \\\$0"; echo shell_exec("/bin/bash -c \"$cmd\"");'
查看更多
Fickle 薄情
3楼-- · 2019-02-26 11:22

Assuming that:

  1. your PHP script is executed by the web server (say, Apache)
  2. the web server is executed with the rights of a special user account,

one of the possible (but not optimal) solutions would be to change the default shell of the user account under which your web server is executed.

查看更多
混吃等死
4楼-- · 2019-02-26 11:31

It probably reads the SHELL environment variable. Disregard that, putenv() didn't work.

Try to just run the command you want with bash, like

shell_exec("bash script.sh");
查看更多
登录 后发表回答