1

I have a PHP script which calls a python script. The Python script does a simple write to file function.

Python:

f = open("xxx", "w")
f.write("xxxxxx")
f.close

PHP:

$output = system("python /home/xxxx/training/scripts/load.py);
echo $output;

If I run the Python directly, it is able to create and write to the file. But when I use the PHP to call it, no file will be created and written. Is that because of some system path related issue? How to fix it?

p.s. If I run a "whoami", it shows the user as "apache". Is that the possible reason that the write-to-file failed?

Thanks so much!

Evian
  • 23
  • 6

1 Answers1

1

this python script will have no output and the php code won't save command's output to the variable output instead it will print it immediately, you should use shell_exec for that

E.g.

<?php 
$output = shell_exec("python script.py");
print $output;
?>

anyways,

Tested on Ubuntu Server 10.04. I hope it helps you also on Archlinux.

In PHP:

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

In Python file 'test.py' verify this text in first line: (see shebang explain):

#!/usr/bin/env python

Also Python file should have correct privileges (execution for user www-data / apache if Php script runs in browser or through curl) and/or must be "executable". Also all commands in .py file must have correct privileges.

chmod +x myscript.py

Source: Running a Python script from PHP

Community
  • 1
  • 1
Abdallah Alsamman
  • 1,623
  • 14
  • 22