How Do You Get a PHP Program to Invoke a Python Program via Browsing a Website?

Problem scenario
You want Debian/Ubuntu Linux to support a website. You want a Python program to run every time a web page is downloaded. How do you get a PHP program to invoke a Python program on Debian/Ubuntu Linux?

Solution

Prerequisites
i. This assumes you have Apache2 and PHP installed. If you need assistance run this: sudo apt -y install apache2 php
ii. This assumes that you have installed Python 3. If you need assistance, run this: sudo apt -y install python3

Procedures
Have a PHP program like this in the same directory as the index.html file:

<?php

   $output = shell_exec('/usr/bin/python3 --version');
   echo $output;

   $output1 = shell_exec('/usr/bin/python3 /foobar/invoker.py');
   echo $output1;
?>

<html>
<body>

HELLO!

</body>
</html>

Put a file called invoker.py in the /foobar/ directory of your server:

#!/usr/bin/env /usr/bin/python3
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('/foobar/output.log')
handler.setLevel(logging.INFO)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the file handler to the logger
logger.addHandler(handler)

logger.info('Hello from contint')

# This was adapted from https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/

Run one of these commands:

sudo chown -R www-data:www-data /foobar
or 
sudo chmod 777 /foobar

Leave a comment

Your email address will not be published. Required fields are marked *