6

I am running a nginx web server, along with PHP-CGI.

I would like to know if it is possible to execute a Python script inside PHP pages, allowing both languages to be combined. I've attempted it briefly but it didn't work, so I'm not sure how I would do this. Here are the two files I used:

index.php

<body>

    <p>Hello! Here is a message: <?php exec('python hello.py'); ?></p>

</body>

hello.py

print 'Hello World!'

Any clues would be appreciated.

3
  • I would do it exactly how you did it. What about it didn't work when you tried that? Could be an issue with the directory python gets executed in. Try an absolute path and see if it works then Commented May 30, 2012 at 1:42
  • The message didn't print on the page. And I tried changing both python and the filename to their absolute paths, still having the issue. Commented May 30, 2012 at 1:45
  • ah I think you need an echo there, didn't see that at first. I posted it as an answer below for reference Commented May 30, 2012 at 1:51

1 Answer 1

4

exec will return the output of the shell command, but you still need to echo that to the page. The following code should work for you

<body>

    <p>Hello! Here is a message: <?php echo exec('python hello.py'); ?></p>

</body>
Sign up to request clarification or add additional context in comments.

2 Comments

This partially works. I tried putting two print commands in my script and it only printed the second one in the page, any idea?
Check out the php docs on exec, the second parameter is a reference parameter called output where the output will be stored if there is multiple lines. This will slightly change the example in this answer obviously

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.