0

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.

2
  • 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')? Commented May 4, 2016 at 2:20
  • Not working it is not executing anything. Commented May 4, 2016 at 5:50

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

2 Comments

I set the variables into putenv, but it is executing only the echo command in the run.sh but run.sh has link to run other bash scripts(with ./ not with sh as sh won't work for that file ) but that is not executing
Great, so you got it executing now. Now it's about figuring out your relative path in bash scripting: unix.stackexchange.com/questions/17717/… , you're probably dealing with relative paths to the scripts your calling within your bash and apache, calling the run.sh script, doesn't know where they are. I think my answer answers your question and you now have an executing script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.