Executing Shell Script from PHP Webpage

Hello ,

I am trying to execute a small shell script from a PHP Webpage.

Below is the shell script : 1.sh

$ cat /home/oracle/rahul/1.sh

#!/bin/ksh
echo "`date` : Report generation in progress" > /home/oracle/rahul/report.txt
echo "Run successfully script";

Below is the PHP Script : index1.php and I copied this file in /var/www/html directory

<?php
        $old_path = getcwd();
        chdir('/home/oracle/rahul/');
        $output = shell_exec("sh 1.sh");
        echo "<pre>$output</pre>";
        chdir($old_path);
?>

When I am trying to run the PHP Script from the command line using : php index1.php then it is executing fine and generating the Output file : /home/oracle/rahul/report.txt however when I am trying to run the url i.e : IPADDRESS/index1.php then it is having problem and I an not able to see anything on my browser.

When run by PHP, it will run as the user and group of the web server, probably apache, which no doubt doesn't have permission to write there and might not even have permissions to execute the script or chdir to that folder.

What are the permissions on the folder and script?

Also, instead of getting the output and pasting it into the script, you could do it more simply as system("./1.sh"); and the output of the script should simply appear in the document directly. system("./1.sh 2>&1"); if you wish to see shell errors too.

Note that the output of your script appears to be something like Run successfully script and absolutely no more.

1 Like