0

I wrote php script (test.php) that calls a python function.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
error_reporting(-1);

echo "php: code started\n";

$command = escapeshellcmd("/usr/bin/python /var/www/html/pythontest.py");
$output = shell_exec($command);
echo $output;
?>

If I call this function from command line as php test.php, it runs perfectly, but when I call this php code from a html page, the code does not run. The html page is showing as it should, though.

My html page is as follows:

<!DOCTYPE html>
<html>
<body>

PHP test page

<?php include 'test.php';?>

</body>
</html>

No errors are reported in /var/log/apache2/error.log

Does anyone have an idea why the php code is not running? Embedding the php code literally in the html file did not work as well. I'm working on an Ubuntu AWS EC2 machine.

Dharman
  • 30,962
  • 25
  • 85
  • 135
EKMEF
  • 1
  • What kind of PHP installation are you using? PHP FPM? mod_php? This is very likely to be a problem in your Apache installation rather than PHP itself. – dmuensterer Jun 09 '20 at 08:15
  • It is unlikely, but if you run PHP < 5.4 you might have safe mode enabled on the webserver which disables `shell_exec`. Also probably stupid question, but did you run the code on the command line on the server or local? If the latter: Is python installed at that location on the webserver? – DBX12 Jun 09 '20 at 08:19
  • So what happens instead? What do you see in the rendered HTML of the page (I e. By looking at the View source feature of your browser)? – ADyson Jun 09 '20 at 08:20
  • 2
    silly question perhaps: the html page is it saved with a `.php` extension? – Professor Abronsius Jun 09 '20 at 08:23
  • 1
    @RamRaider not a silly question at all! I'm embarrassed to admit it, but saving it as index.php instead of index.html did the trick... :-) – EKMEF Jun 09 '20 at 08:38
  • ;-) good stuff - good luck with the rest of the coding adventure – Professor Abronsius Jun 09 '20 at 08:44

1 Answers1

0

shell_exec, exec or other command functions are most time disabled on PHP web hosting of security reasons. On most servers you can enable it. But be carefull if some one manage to inject a command into your exec function you have a big problem

Baracuda078
  • 677
  • 1
  • 5
  • 10
  • What would be a better way to execute python code on a website? – EKMEF Jun 09 '20 at 08:46
  • Im not sure to be honnest, I'm working also on a php project that has to use python scripts. My php script also use shell_exec now. Maybe I try to turn my python script in a simple api so I can call it with PHP curl so I can let the exec function on disabled – Baracuda078 Jun 09 '20 at 09:02