exec function is not working in PHP

5.9k Views Asked by At

in php exec function is not working to run a shell command.

if I run in terminal

   $ avconv -i in.mp4 -f mp3 -ab 192000 -vn rip.mp3 

the command is working fine, the command is for converting a video to mp3. But when I try to execute through PHP it just doesn't work.

   exec("avconv -i in.mp4 -f mp3 -ab 192000 -vn rip.mp3");

or if I try exec("whoami"); is giving me the correct output.

3

There are 3 best solutions below

0
On BEST ANSWER

okay, it was a file permission issue. www-data had not the permission to write the file, after changing the permission it's working now.

3
On

Most likely you need to give the command the full path to your files, because the current dir in PHP is not the same as in your shell.

exec("avconv -i /path/to/in.mp4 -f mp3 -ab 192000 -vn /path/to/rip.mp3");

Maybe even the full path to aconv to be safe:

exec("/bin/avconv -i /path/to/in.mp4 -f mp3 -ab 192000 -vn /path/to/rip.mp3");

Check what is the correct path for aconv with which aconv.

To check for any error, add a second parameter to the exec command and print it:

exec('...', $result);
var_dump($result);
0
On

You need to follow these steps.

  • First check the exec() function exists or not.

    if(function_exists('exec')){
       echo 'Function exists';
    }else{
       echo 'Function does not exists';
    }
    
  • If it exists then you may have the syntax error in your exec code. If it does not exists check it is disabled under php.ini by using the function given below.

    function disabled_functions(){
      $disabled = explode(',', ini_get('disable_functions'));
      return $disabled;
    }
    echo "<pre>";
    print_r(disabled_functions());
    

    The above function will list out all the disable functions in php.ini.

  • If exec exists in the output of the above disabled_functions(). Then go to /etc/php.ini and remove exec from disable_functions

  • After saving php.ini file restart php-fpm. In case of Redhat/CentOS 7 and Fedora. sudo systemctl restart php-fpm

In case if you are using Cpanel and WHM Panel

  • The exec may not be listed in disable_functions of php.ini file.

  • Login in from WHM Panel, go to MultiPHP Manager, click on System PHP-FPM Configuration Tab, then go to Disabled Functions. Now from here remove the exec.

  • After removing save it and restart PHP-FPM.

  • In case you do not have WHM Panel access you may not be able to use this function. So request your hosting provider for shell access and exec for your account only.