The Apache’s user www-data need to be granted privileges to execute certain applications using sudo.

  1. Run the command sudo visudo. Actually we want to edit the file in etc/sudoers.To do that, by using sudo visudo in terminal ,it duplicate(temp) sudoers file to edit.
  2. At the end of the file, add the following ex:-if we want to use command for restart smokeping and php command for another action in your question,

www-data ALL=NOPASSWD: /etc/init.d/smokeping/restart, usr/bin/php

(This is assuming that you wish to run restart and php commands using super user (root) privileges.And you use php command in usr/bin/ path )

However, if you wish to run every application using super user privileges, then add the following instead of what’s above.You might not want to do that, not for ALL commands, very dangerous.

www-data ALL=NOPASSWD: ALL

3.After edit the sudoers file(by visudo we edit the temp file of sudoers so save and quit temp file(visudo) to write in sudoers file.(wq!)

4.That’s it, now use exec() or shell_exec in the following manner inside your xxx.phpscript.keep remember to use sudo before the command use in the php script.

ex:-

exec ("sudo /etc/init.d/smokeping restart 2>&1");

or

shell_exec("sudo php -v"); 

So in your problem,add the commands that you wish to use in to the step no (2.) as I add and change your php script as what you want.

here is the same problem as yours https://stackoverflow.com/a/22953339/1862107

Answer from Thusitha Sumanadasa on Stack Exchange
Top answer
1 of 6
12

The Apache’s user www-data need to be granted privileges to execute certain applications using sudo.

  1. Run the command sudo visudo. Actually we want to edit the file in etc/sudoers.To do that, by using sudo visudo in terminal ,it duplicate(temp) sudoers file to edit.
  2. At the end of the file, add the following ex:-if we want to use command for restart smokeping and php command for another action in your question,

www-data ALL=NOPASSWD: /etc/init.d/smokeping/restart, usr/bin/php

(This is assuming that you wish to run restart and php commands using super user (root) privileges.And you use php command in usr/bin/ path )

However, if you wish to run every application using super user privileges, then add the following instead of what’s above.You might not want to do that, not for ALL commands, very dangerous.

www-data ALL=NOPASSWD: ALL

3.After edit the sudoers file(by visudo we edit the temp file of sudoers so save and quit temp file(visudo) to write in sudoers file.(wq!)

4.That’s it, now use exec() or shell_exec in the following manner inside your xxx.phpscript.keep remember to use sudo before the command use in the php script.

ex:-

exec ("sudo /etc/init.d/smokeping restart 2>&1");

or

shell_exec("sudo php -v"); 

So in your problem,add the commands that you wish to use in to the step no (2.) as I add and change your php script as what you want.

here is the same problem as yours https://stackoverflow.com/a/22953339/1862107

2 of 6
5

Try specifying the entire path to the php binary.. Eg, /usr/bin/php

If you don't know it, find it using: which php

Discussions

Shell_exec is not working
I am trying to execute a command with shell_exec but this command does not work, other commands work $output"; ?> More on unix.com
🌐 unix.com
0
0
September 20, 2019
linux - PHP shell_exec() doesn't work but commands work from console - Stack Overflow
I'm following this guide for deploying ... with PHP shell_exec() or exec(). The deploy script runs several commands such as git, whoami, which git, rsync, etc. All of these commands work when I'm logged in as the server user. However, when I hit the php script that is supposed to run these commands, they don't work. whoami: command not ... More on stackoverflow.com
🌐 stackoverflow.com
Executing a shell command from PHP with shell_exec - Unix & Linux Stack Exchange
I am trying to perform this with an execution of a shell command in a PHP file. Why doesn't this work (below is just a specific example - not the general code that I am using)? More on unix.stackexchange.com
🌐 unix.stackexchange.com
June 19, 2011
PHP exec() not working | php.ini is fine
Hi, I’ve seen few topics but nothing worked. My php.ini doesn’t block exec() or shell_exec(), but yet the shell command from php doesn’t execute. It works only from the terminal. I gave folder permissions to user: cyberpanel: still not working Please help Thanks More on community.cyberpanel.net
🌐 community.cyberpanel.net
1
0
March 7, 2023
🌐
PHP
php.net › manual › en › function.shell-exec.php
PHP: shell_exec - Manual
I wanted to run Ghostscript via ImageMagik's "convert" and ended up having to add my path before running the command: <?php $cmd = 'export PATH="/usr/local/bin/"; convert -scale 25%x25% file1.pdf[0] file2.png 2>&1'; echo "<pre>".shell_exec($cmd)."</pre>"; ?> ALSO, note that shell_exec() does not grab STDERR, so use "2>&1" to redirect it to STDOUT and catch it. ... Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work.
Top answer
1 of 2
3

There's multiple problems here.

  1. Do people even read the error messages they get?
  2. Don't use shell commands to read a file to a variable! Use fopen.
  3. Don't do globbing. Globs are expanded by the shell, but PHP is not a shell, so it doesn't do globbing. It hands your exact command off to the shell, and asks the shell to execute it. And yes, *-release is a valid filename.
    [~]$ ls -la /tmp/\*-releases 
    -rw-r--r-- 1 vidarlo users 0 Jun 23 10:16 /tmp/*-releases
    [~]$ 
  1. Globbing potentially opens you to attacks. If you glob, you have no control over what files you end up reading. That's a potential security issue. Probably not in this case, as you're reading from /etc, but...
  2. You lack a basic understanding about your environment, when you expect that modifying a path parameter will change anything - the problem is not that cat command is not found, it's that the file you give as parameter is not found... A general understanding of the platform is a good starting point for programming.
  3. putenv('/etc'); is not how putenv works. Environment variables are generally key=value-pairs.
  4. Don't post it on serverfault. It's not about managing IT, it's purely about programming. Additionally, you should probably spend some time to learn the platform you're working on.
2 of 2
0

The problem was that PHP was setup to run in chroot jail. I had exhausted all other possibilities. I only even discovered it thanks to @vidarlo's comment.

I was able to resolve the issue in WHM via the CageFS plugin. The Linux user that PHP uses was set to execute and I removed it from the association.

🌐
Super User
superuser.com › questions › 781412 › unable-to-start-bash-script-with-shell-exec
linux - Unable to start bash script with shell_exec - Super User
I've been googling and trying to solve this problem with my php script for a few days now and I'm hoping someone here can see the problem I'm missing in getting my php script to kick off my bash script. ... //kickoff the yapeal script echo "Starting yapeal.sh<br>"; echo "Current working directory: "; echo getcwd() . "\n"; shell_exec('./yapeal.sh'); echo "<br>yapeal.sh ran, I hope.<br>";
🌐
Unix.com
unix.com › unix for beginners q & a
Shell_exec is not working - UNIX for Beginners Q & A - Unix Linux Community
September 20, 2019 - I am trying to execute a command with shell_exec but this command does not work, other commands work <?php $output = shell_exec("tail /var/log/syslog"); echo "<pre>$output</pre>"; ?>
Find elsewhere
Top answer
1 of 1
6

By the looks of it your PATH variable only includes /bin. This only allows you to run executables within that directory. There are a few ways to fix this.

Method 1: Configure the web server environment varibles

If you are running apache, you can simply edit /etc/apache2/envvars to include a PATH varibale definition. Edit the file and add a new line to the bottom (if it doesn't already exist):

# /etc/apache2/envvars
...

export PATH="/bin:/usr/local/bin"

Method 2: Configure the PATH for the user

Alternatively, if you are running the web server as a user other than a service user, that user may not have their PATH properly configured. This is as simple as changing their environment variables for the user and the web server will inherit it (unless defined otherwise in the web server's configuration).

First step is figure out which user your web server is running as. If you don't know, you can check list the running processes to find the user. This can be accomplished by running the following command:

ps aux|grep {webserver}|grep -v grep Where {webserver} is replaced with the web server you are currently running. (apache/httpd, nginx)

Alternatively, you can check in of the following config files:

  • /etc/httpd/conf/httpd.conf - CentOS Apache
  • /etc/apache2/apache2.conf - Ubuntu/Debian Apache
  • /etc/nginx/nginx.conf - nginx config

(There are many other possible configurations, but these are the most common)

Once you've found out which user you're running as, you will need to then set the PATH variable for that user. This could be as simple as exporting the PATH in their home bash configuration. This could be /home/bob/.bashrc for example. Service users without a home will be different however.

Method 3: Declare the PATH within your PHP script

You can manually specify the PATH variable within your PHP script. This can be accomplished by adding the following line to your script:

<?php

putenv('PATH=/bin:/usr/local/bin');
...

You will need to change the PATH to suit your needs, and it will need to be declared before you call shell_exec().

This method isn't preferred as you will need to specify this for each PHP script you execute that makes use of the shell_exec() call to binaries outside of /bin, but it is a quick one off solution that will work.

More importantly, you are writing code that is not portable and is dependent on a specific system. This is bad coding practice and is not recommended/frowned upon.

🌐
CyberPanel Community
community.cyberpanel.net › support and discussion › general discussion
PHP exec() not working | php.ini is fine - General Discussion - CyberPanel Community
March 7, 2023 - Hi, I’ve seen few topics but nothing worked. My php.ini doesn’t block exec() or shell_exec(), but yet the shell command from php doesn’t execute. It works only from the terminal. I gave folder permissions to user: cy…
🌐
Stack Overflow
stackoverflow.com › questions › 28714060 › php-command-does-not-work-with-php-shell-exec
linux - php- command does not work with php shell_exec - Stack Overflow
March 3, 2019 - <?php $fname = $_POST['fname']; $fpack = $_POST['fpack']; $email = $_POST['email']; //Creating a new Android project var_dump(shell_exec("android create project --target 8 --name $fname --path ./$fname --activity MainActivity --package $fpack 2>&1")); ?> When I run my PHP script I get the following output: string(26) "sh: 1: android: not found " Why it works when I enter manually in terminal (from user 'ashish' account) but not with php? my apache user and group is same (ashish). Any help will be appreciated :) php · linux ·
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › using the raspberry pi › troubleshooting
PHP Command shell_exec with Apache - Raspberry Pi Forums
The error messages should be in /var/log/apache2/error.log. You should revert all your changes of ownership and permissions in /var/www. www-data should not have write permission for files below this directory. You should use "." instead of "+" if you want to concatenate strings in PHP.
🌐
Reddit
reddit.com › r/phphelp › php shell_exec not working with pipes
r/PHPhelp on Reddit: php shell_exec not working with pipes
May 28, 2022 -

Hi all I'm trying to SvtAv1EncApp tools via web interface, I try to us both exec() shell_exec() with no success , BTW I print the command and run it into the shell directly and it's works perfectly fine.

$cmd2="/usr/local/bin/ffmpeg -loglevel -8 -i "$mp4" -s 960x540 -strict -1 -f yuv4mpegpipe - | /usr/local/bin/SvtAv1EncApp --no-progress -i stdin --rc 0 -q 38 --preset 8 -b stdout 2>/var/www/vl/ffmpeg.log | /usr/local/bin/ffmpeg -loglevel -8 -y -i - -i "$mp4" -map 0:v -map 1:a:0 -c:v copy $a '".$mpa."_.mkv' & ";

shell_exec( $cmd2 ) ;

Here is the text of echo $cmd2 output

/usr/local/bin/ffmpeg -loglevel -8 -i "FHD.mp4" -s 960x540 -strict -1 -f yuv4mpegpipe - | /usr/local/bin/SvtAv1EncApp --no-progress -i stdin --rc 0 -q 38 --preset 8 -b stdout 2>/var/www/vl/ffmpeg.log | /usr/local/bin/ffmpeg -loglevel -8 -y -i - -i "FHD.mp4" -map 0:v -map 1:a:0 -c:v copy -strict -2 -c:a libopus -b:a 64k 'FHD_.mkv' &

=Update=

I kinda solve it , I don't know why but exec() successfully executed the script , I created new bash script from command line thanks to @xisonc suggesting nano /usr/local/sbin/av1c with this value

!/bin/sh

touch /var/www/vl/ffmpeg.log /usr/local/bin/ffmpeg -loglevel -8 -i "$1" -s 960x540 -strict -1 -f yuv4mpegpipe -
| /usr/local/bin/SvtAv1EncApp --no-progress -i stdin --rc 0 -q 38 --preset 8 -b stdout 2>/var/www/vl/ffmpeg.log
| /usr/local/bin/ffmpeg -loglevel -8 -y -i - -i "$1" -map 0:v -map 1:a:0 -c:v copy -strict -2 -c:a libopus -b:a 64k "$2"

On the php script i had this

$cmd2="/usr/local/sbin/av1c '$mp4' '$mpa"."_.mkv'   2>/dev/null >/dev/null & " ; 
exec( $cmd2 , $pid, $r )    ;   
var_dump(  $r )                ;

var_dump returns 0 , and since the bash script are silent I don't need to see the output , now I want to change it to wok on the background it's running on background now after adding 2>/dev/null >/dev/null & at the end of the command .

🌐
Reddit
reddit.com › r/phphelp › shell_exec not working
r/PHPhelp on Reddit: Shell_Exec not working
November 5, 2021 -

Hello,
I have a php script that execute a Shell. It is supposed to execute a .ps1 when i request the page.
It was working fine but a coworker had to reboot the IIS VM running php 8 with CGI. The script is not working anymore and is giving me a blank page when i request it.

<?php echo Shell_exec ('Powershell.exe -ExecutionPolicy Bypass -NoProfile -File ".\dev.ps1"'); ?>

What i did so far :

  • Checking the php.ini file to make sure Shell_exec wasn't in Disable_functions="".

  • Changing the FastCGI Protocol configuration from "Named pipe" to "TCP"

  • Rebooting, of course

Thanks,

Top answer
1 of 2
1

1) Check the security setup

Can shell_exec() be run or not? If it can't then it's because you are having some security settings enabled.

The problem is that shell_exec() and exec() can be disabled for security reasons. This can be changed by editing PHP's disable_functions option.

INI settings are usually stored in specific *.ini files under the /etc/php/* directories. So you have to look for some settings in there. You’ll find several INI settings, depending on how PHP is run. To find them :

find /etc/php/ -iname 'php.ini'

This could output something like this :

/etc/php/8.2/fpm/php.ini
/etc/php/8.2/apache2/php.ini
/etc/php/8.2/cli/php.ini
/etc/php/8.2/cgi/php.ini

To see the settings and which INI file is loaded, add this at the beginning of your script and call it via your web server :

phpinfo();
die();

You'll see all the loaded INI files and what is set on the disable_functions option.

/etc/php/8.2/cli/php.ini is probably setting disable_functions to an empty string, meaning that in command line there's no restriction. But for the other INI files, this option might contain a list of functions that you won't be able to run. Edit this option if needed. But be always aware that giving your server the ability to run some binaries can lead to some security issues if your app is taking some user input to build the command.

Apache configuration can also set some PHP settings, just for a specific Virtual Host. So have a look at them if you can't find something in the php.ini files.

Depending on your PHP setup, you may also have to check safe_mode and suhosin.executor.* if you have the Suhosin hardening module installed.

2) Verify that you can run shell_exec

There are several ways to run a binary. shell_exec is equivalent to the built-in backtick operator. So if shell_exec is listed in the disable_functions option then you won't be able to use the backtick operator.

If you get an error 500 then it's typically because you cannot run shell_exec. If you check /var/log/nginx/error.log or /var/log/apache2/error.log with this command :

sudo tail -f /var/log/{apache2,nginx}/error.log

It will print both logs until you press CTRL+C. You may see this error :

PHP Fatal error:  Uncaught Error: Call to undefined function shell_exec()

PHP also offers exec(), passthru(), system(), and the proc_*() functions. So you've got several possibilities to try and run your command.

Have a try with a simple PHP code :

<?php

header('Content-Type: text/plain; charset=utf-8');

echo 'PHP user given with the "id" command: ' . `id`; // equivalent to shell_exec('id');
echo 'System date is ' . `date --iso-8601=seconds`;

This should output RAW text in your browser with :

PHP user given with the "id" command: uid=33(www-data) gid=33(www-data) groups=33(www-data)
System date is 2023-09-29T11:50:28+00:00

3) Use a full path to the binary

When shell_exec() is run from the web server, it's rather common that the binary isn't found in the PATH. Usually, the www-data user running PHP won't even have a shell. But this user can normally run some binaries, except if some settings at point 1 is blocking it.

To find the full path to a binary, use the which command :

which wkhtmltopdf

This should output the full path to the binary. Certainly something such as /usr/bin/wkhtmltopdf.

Now replace your PHP code with the full path to the binary:

header('Content-Type: text/plain; charset=utf-8');
echo shell_exec('/usr/bin/wkhtmltopdf --version');

Does it print wkhtmltopdf 0.12.6 like expected?

If no, then we have to investigate more at the next point.

4) Get the execution output and find errors

This can be done with the help of exec(), passthru() or system() as they all return the execution status code.

With the proposition of Volkerschulz, we'll also redirect the standard error stream to the standard output stream so that we can see some details that may have only be printed to the error stream.

This is done by redirecting stderr (2) into stdout (1) by adding 2>&1 after your command.
Just as info, stdin is 0.

In PHP, this becomes :

<?php

header('Content-Type: text/plain; charset=utf-8');

$command = '/usr/bin/wkhtmltopdf --wrong-option 2>&1';

$last_line = exec(
  $command,    // The command to execute.
  $output,     // A variable that will be filled with an array of all the lines returned.
  $result_code // The return status of the executed command.
);

var_export([
  '$command' => $command,
  '$output' => $output,
  '$last_line' => $last_line,
  '$result_code' => $result_code,
]);

This outputs :

array (
  '$command' => '/usr/bin/wkhtmltopdf --wrong-option 2>&1',
  '$output' => 
  array (
    0 => 'Unknown long argument --wrong-option',
    1 => '',
    2 => 'Name:',
    3 => '  wkhtmltopdf 0.12.6',
    ...
    ...
    95 => '',
  ),
  '$last_line' => '',
  '$result_code' => 1,
)

Now I'm able to see that I got a $result_code of 1 instead of 0.

In case the executable is having other errors, you'll see them in the $output array as the stderr stream should be visible. This should help you find how to fix the issue. Probably some other security problems due to the fact the www-data user might be missing some rights, paths or whatever.

PS: On my Vagrant box of Ubuntu 22.04, I managed to run wkhtmltopdf without errors on both Apache and NGINX.

Don't forget also that your www-data user should have write access to the destination folder where you are producing the PDF file.

5) Try re-installing wkhtmltopdf and/or use a PHP wrapper

You might have to re-install wkhtmltopdf if it's not properly working :

sudo apt remove wkhtmltopdf
sudo apt autoremove
sudo apt install wkhtmltopdf

You can also try using a PHP wrapper library for wkhtmltopdf called Snappy. It might be useful.

6) Switch to an alternative in pure PHP if necessary

Perhaps you won't manage to make wkhtmltopdf work that easily. It's a pity as it's effectively a fast and reliable solution.

But to create a PDF from HTML you could also use the Dompdf PHP library. I've used it in the past and was happy with it.

2 of 2
0

Instead of

shell_exec($wkhtmltopdfCommand);

try

$result = passthru($wkhtmltopdfCommand . ' 2>&1');
var_dump($result);

and it should tell you what's wrong.

🌐
GitHub
github.com › php › php-src › issues › 13257
PHP Bug when using `shell_exec` on Centos Stream and also 8. · Issue #13257 · php/php-src
January 26, 2024 - <?php echo shell_exec('sudo echo "aa" > /a.txt'); ?> If I run this using the command line php test.php it all works fine. However if I try to access domain.com/test.php in the browser (I am using all default configurations from Apache/PHP, nothing changed) the file never gets created and no error message it shown anywhere.
Author   batata004