PHP: How to fix error shell_exec can’t run some command on Linux


Example you create file 1.php with content:

<?php
$output = shell_exec('/usr/bin/ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "/home/tutorialspots/tutorialspots.mp4"');
echo "<pre>$output</pre>";
?>

If you run this command with root:

php 1.php

It work well

[root@tutorialspots tutorialspots]# php 1.php
<pre>38.823767
</pre>

But if you run under HTTP: http://tutorialspots.com/1.php it doesn’t work

<pre></pre>

So strange!

Step 1: we need to know our current user that our http server uses. Create file 2.php with content

<?php
echo shell_exec("whoami");
?>

Run this with http server (we use nginx and php-fpm): http://tutorialspots.com/2.php and see:

php-fpm

We know current user is php-fpm.

Step 2: run this command with root

visudo

Then add this line

php-fpm ALL=NOPASSWD: ALL

Save.

visudo

Step 3: check, create file 3.php with content:

<?php
echo shell_exec("sudo whoami");
?>

Go to address http://tutorialspots.com/2.php you will see:

root

Step 4: Done, now with all command you must use with sudo, my example:

<?php
$output = shell_exec('sudo /usr/bin/ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "/home/tutorialspots/tutorialspots.mp4"');
echo "<pre>$output</pre>";
?>

Result:

<pre>38.823767
</pre>

1 Comment

Leave a Reply