2

My default Web-Application is based on PHP. However, for easiness, I have built a python script that does some analysis. Now I need the php to call the python code and retrieve the output that the python code delivers. Both files are in the same server, not on the same folder however. My current approach, which does not work, looks as following:

$cmd = "/usr/bin/python /var/www/include/sCrape.py -u '$my_url' ";
$response = shell_exec($cmd);
$response = json_decode($response, true);

Now when I try to print out $response, I get the NULL object (it should return an array-string that I should decode through json_decode). Am I doing something wrong with the function? The php is located within /var/www/html/. The following code works when both files are in the same directory:

$cmd = "python sCrape.py -u '$my_url'";
$response = shell_exec($cmd);
$response = json_decode($response, true);

Further information: my_url is input as a sanitized $_POST variable from php, but I have now tried to completely disable sanitizing to test if it would work, but it still didn't (still, the url's path until it reaches the function is longer, as it must be passed on through form-post, whereas in my same-folder-test-case I have simply just declared $my_url). the -u postfix means that the script inputs a url.

Thank you very much in advance!

DaveTheAl
  • 1,995
  • 4
  • 35
  • 65

1 Answers1

2

Did you try running /usr/bin/python /var/www/include/sCrape.py -u '$my_url' in a shell? The mistake is probably there.

Try:

$cmd = "/usr/bin/python /var/www/include/sCrape.py -u '$my_url' 2>&1";
$response = shell_exec($cmd);
echo $response;

This should output an error message.

Why?

shell_exec only returns output from the standard output (stdout), if an error occurs it's written "to the" standard error (stderr). 2>&1 redirects stderr to stdout. See In the shell, what does “ 2>&1 ” mean?.

Run python code

You may want to add #!/usr/bin/env python on the first line of your python script and make it executable chmod +x /var/www/include/sCrape.py. Afterwards you should be able to run your script without explicitly calling python. /var/www/include/sCrape.py -u '$my_url'

Community
  • 1
  • 1
Liblor
  • 480
  • 5
  • 13
  • Thank you very much for the extensive answer! However, that unfortunately did not solve my problem :/ anything else you could think of? could it be that the post sanitizing destroys the url? – DaveTheAl Mar 05 '16 at 18:12
  • What was the value of `$response` with `2>&1` added? I think it's a permission problem. – Liblor Mar 05 '16 at 18:29
  • Dude, please give yourself a hug... the 2>&1 within the shell_exec worked well and I can finally debug my code... Thank you very mcuc! – DaveTheAl Mar 06 '16 at 18:17
  • could you maybe have a look over this aswell? http://stackoverflow.com/questions/35830893/cant-import-nltk-from-within-phps-shell-exec – DaveTheAl Mar 06 '16 at 18:48