'PHP - how to terminate python script from php page?

I am currently working on my final year project which is IoT based. I have a website written in php and I have sensors which are controlled by the raspberry pi board using python script. One of the functions I want to develop is that the user can control the sensors by turn them on/off via the web page. what I mean by turning on/off is to run or terminate python script from running.

I could execute the python file from the web page and it works fine using shell_execute(python fileName.py). however for the termination, I could not, even I tried different ways to do so. The problem I have faced is the script keeps running in the background.

Please help if anyone has an idea of how to stop python script from web page(php page - pressing a button for example).

Thank you



Solution 1:[1]

From terminal

sudo visudo 

Add

www-data  ALL=(ALL) NOPASSWD: /usr/bin/kill

Create a PHP file and add

<?php
shell_exec ('sudo kill -9 $(pgrep -f python)');
?>

You can make a button to call the PHP file to kill all running Python processes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rijotech