1

Why am I not able to execute this bash script using php? I have tried exec() as well as shell_exec().

index.php

<?php
$old = getcwd();
echo $old;
chdir($old);
$message=exec("a.sh");
print_r($message);
?>

a.sh

#!bin/bash
echo "i am a" > /opt/lampp/htdocs/a.txt
echo "Done"

I have tried chdir as suggested here, as well as I have checked my disable_functions in php.ini, it doesn't have anything. I have also checked other questions, but none seem to solve my problem.

  • 1. Why don't you give the full path to the script? 2. Why are you doing chdir($old) twice? Is that a typo? – muru Sep 5 '14 at 17:15
  • I have tried that too. But echoing $old shows the correct path of a.sh. As index.php and a.sh are in the same dir. chdir was there because I copied that from somewhere, then edited the 1st chdir but not the second. – Optimus Prime Sep 5 '14 at 17:28
  • 1
    Alright, what do the apache logs say? Any mention of an error? – muru Sep 5 '14 at 17:33
  • 1
    Does a.sh have #!/bin/bash as the first line? Have you tried exec("/bin/bash a.sh") – Dan Sep 5 '14 at 17:35
  • 1
    Aha did not see that BUT you need a leading slash before bin so it reads #!/bin/bash – Dan Sep 5 '14 at 17:44
2

First, be sure that the shebang is exactly as follow:

#!/bin/bash

Second, be sure that the script is executable using the following command in terminal:

chmod +x /path/to/a.sh

And third, you must to use the full path for the bash script, or in your case, you can use:

$message=exec("$old/a.sh");

And, as an aside note, the following two commands from your php script have no sense:

$old = getcwd();
chdir($old);

They are equivalent with chdir(getcwd()), which change the current directory to ...the current directory, so in fact, nothing happens.

| improve this answer | |
  • 2
    @OptimusPrime Well, check again, you said in your Q that your bash script starts with #!bin/bash, not #!/bin/bash as I said which obviously are not the same – Radu Rădeanu Sep 5 '14 at 17:47
  • Sorry about previous comment. I did not see that clearly. I have made the file executable. But it still does not write that file a.txt. What else may be the problem? – Optimus Prime Sep 5 '14 at 17:51
  • Permissions problem, plenty of info on this site and around the web. – Dan Sep 5 '14 at 17:54
  • @RaduRădeanu Yes, I realize they have no effect. But I just copied that from web, and was trying them if they could solve the problem. – Optimus Prime Sep 5 '14 at 17:59
  • @dan08 Yes, I changed the permissions and it worked. You were right again. – Optimus Prime Sep 5 '14 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.