'php shell_exec with sudo commands not working

I have made a file test.php in (/opt/lampp/htdocs/xampp/test.php) containing code

$data = shell_exec("sudo php -v"); 
var_dump($data);

but it gives me result NULL

I am using PHP 5.6.11-1ubuntu3.1 (cli), so i have added line in /etc/sudoers file also

www-data ALL=NOPASSWD: /opt/lampp/htdocs/xampp/test.php

I have also tried by adding

www-data ALL=NOPASSWD: ALL

But nothing seems to work. Please help



Solution 1:[1]

  • Edit the sudoers file (with visudo) and add a rule that allows the web server user to run the command without a password. For example:

    www-data ALL=NOPASSWD: /path/to/script
    

    This will allow that particular user to call sudo on that particular script without being prompted for a password.

  • Try specifying the entire path to the php binary.. /usr/bin/php, If you don't know it, find it using: which php

    $data = shell_exec("/usr/bin/php -v"); 
    var_dump($data);
    
  • You can also check your php.ini restrict the available command set ?

    ; When safe_mode is on, only executables located in the safe_mode_exec_dir
    ; will be allowed to be executed via the exec family of functions.
    ; http://php.net/safe-mode-exec-dir
    safe_mode_exec_dir =
    

Solution 2:[2]

You should change minimum uid/gid for mpm_itk module:

$ cat /etc/apache2/modules.d/00_mpm_itk.conf
<IfDefine MPM_ITK>
LoadModule mpm_itk_module modules/mpm_itk.so
#  LimitUIDRange 1000 2000
#  LimitGIDRange 1000 2000
  LimitUIDRange 0 2000
  LimitGIDRange 0 2000
</IfDefine>

Solution 3:[3]

sudo adduser USERNAME

sudo usermod -aG sudo USERNAME

you need to create a new user in ubuntu if you are login with default credentials then switch to a newly created user.

Here you just need to replace USERNAME with your new one

su - USERNAME

in last you can use every command with sudo

shell_exec('echo "yourpassword" | sudo -u yourusername -S | sudo --version')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DevLoots
Solution 2 Drew
Solution 3 hamza mughal