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!

6
  • Is your file path relative or fully specified? Could be a working directory issue. Commented Sep 13, 2015 at 6:40
  • Could be anything. Where's the php side? If you want answers, provide everything. Commented Sep 13, 2015 at 6:43
  • 1
    If by "use PHP" you mean calling it via browser, maybe the user that runs the webserver (in debian-based it would be wwwdata, in redhat-like httpd, I think) doesn't have write permission in the target dir. Commented Sep 13, 2015 at 7:38
  • Hi I am using absolute path, not relative. Commented Sep 13, 2015 at 8:46
  • Yes, what i meant by "use PHP" is calling it via browser. But that directory is in 777 Commented Sep 13, 2015 at 8:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Abdallah, sorry I was my typo here. What I did in my script is f = open("xxx", "w")
Hi @Abdallah, I have updated the question with code.

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.