Run bash script from php

59,526

You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.

$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);
echo "<pre>$output</pre>";
Share:
59,526

Related videos on Youtube

foobarPho
Author by

foobarPho

Updated on September 18, 2022

Comments

  • foobarPho
    foobarPho over 1 year

    I want to run a shell script within a php webpage to check some processes running on my system (Ubuntu 12.04). Googleing I've found about shell_exec() but I can't manage to run the script when loading php.

    This is the php code I use.

    $output = shell_exec('./dirlist.bash');
    echo "<pre>$output</pre>";
    

    and the piece of html I get

    <pre></pre>
    

    Also tried $output = shell_exec('sudo -u www-data ./dirlist.bash');

    dirlist.bash does ls -l (just for testing script and shell_exec)

    I think it is not a permission problem. Running directory grants write and execute privileges for all users (I should be careful here).

    drwxrwxrwx  4 meteo meteo 4096 mar 11 15:20 RAMS
    

    User www-data has been added to sudoers file in case it was needed

    www-data ALL = (meteo) NOPASSWD: /home/meteo/www/RAMS/dirlist.bash
    

    Thanks in advance

    • Admin
      Admin about 10 years
      Programming questions are off topic here unless they are directly related to administering your system. I suggest you ask on Stack Overflow, but your problem is almost certainly that you are using relative paths (./dirlist_bash). And for the love of all that's fluffy, remove www-data from sudoers!
    • Admin
      Admin about 10 years
      You are right, I will move to Stack Overflow. And as you ask so kindly I will remove www-data :-)
    • Admin
      Admin about 10 years
      Hi, now using absolute path it is running fine, thank you very much.
    • Admin
      Admin over 9 years
      can you post a link to your question on SO here in the comments for others who follow? thanks!
    • Admin
      Admin over 9 years
      There it is link
  • Oli
    Oli about 10 years
    This has a disturbing similarity to a block of code on SO. Give credit.