How to execute shell script files from PHP or HTML. The sh file is located outside the localhost directory, and there are many other sh files which are initiated by the first sh file.
say the local host directory is
/opt/lampp/htdocs/xampp/test
and the location of the sh file is /home/user/scripts/run.sh.
run.sh copies some files uploaded from /opt/lampp/htdocs/xampp/test/upload to /home/user/scripts/file and execute some other .sh files.
I have tried many PHP methods with no success like
<?php $output = shell_exec('sh /home/user/script/run.sh'); echo "$output"; ?>
and
<?php
shell_exec("/home/user/server/run.sh");
?>
but no luck. I could not put the sh file in CGI directory as it is dependent on other script and files. How do I run the script from the directory it currently presents.
-
have you tried changing working directories in php before executing the shell script, by using either chdir("/home/user/scripts/") or shell_exec('cd /home/user/script/ sh /home/user/script/run.sh')?gmfm– gmfm2016年05月04日 02:20:43 +00:00Commented May 4, 2016 at 2:20
-
Not working it is not executing anything.anonymous– anonymous2016年05月04日 05:50:25 +00:00Commented May 4, 2016 at 5:50
1 Answer 1
It's most likely the case that you do not have any environment variables setup as the user who is executing the script from php. It's probably username group apache:apache. You should setup some environment variables for PATH so it knows where the executables are. You could alternatively point sh to /usr/bin/sh:
<?php $output = shell_exec('/usr/bin/sh /home/user/script/run.sh'); echo "$output"; ?>
Or log onto the server and echo $PATH. Then copy paste that into the putenv function:
putenv('PATH={your_paths}');
$output = shell_exec('sh /home/user/script/run.sh'); echo "$output";