3

I'm working on a program that utilizes Python scripts that pull information from a MySQL database. The MySQL database is managed from a PHP site interface (so HTML forms and buttons and the such). I have this all set up on a raspberry pi and it works. But I want to add some more functionality.

Specifically I want to be able to execute certain python scripts from the PHP site. I want it to be as simple as a press of a button, literally.

Is this a scenario where I should use Django? I've never used it before but have read about how it connects Python with the web. I found an answer to a similar question but I'm wondering If I need to set up anything special on my apache server: https://stackoverflow.com/a/31811462/5609876

I even made a little picture for a visual representation of my program incase my explanation wasn't good enough:

enter image description here

Community
  • 1
  • 1
E.Arrowood
  • 750
  • 7
  • 17

2 Answers2

3

No, you do not need django at all.

If all you want to do is execute a Python script from PHP - assuming you have already written the script and stored it somewhere:

First, assign execute permissions on the Python script to the user that is running the PHP code. Normally, this is the same user that is running Apache. Usually this is called www-data or apache or something similar. The user will be listed in the Apache configuration file.

Then, on your PHP side, all you really need is exec:

<?php

    exec('/path/to/python /path/to/your/script.py')

?>
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

If the shell_exec function is allowed on your server, you can use that to run your Python script through Bash. shell_exec returns the output of the bash call. The only thing you have to make sure of is that shell_exec isn't disabled in your server's php.ini file (look for the line disable_functions shell_exec).

If your python script is called mypythonscript.py and is in the same directory as the PHP file, you can run it like this:

<? shell_exec('python mypythonscript.py'); ?>