Home » Php » Activate Python script with HTML Button + PHP Combination

Activate Python script with HTML Button + PHP Combination

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to make an online webserver controller for some LED strips. After spending hours of research I am stumped and yet haven’t felt closer to what I want.

As seen below I have an HTML Script and PHP script. If I click “on” it does successfully activate the on function in php (tested through echo’s and alert boxes).

Yet the python command does not work. I have tested just running php -f ajax.php and the else method worked and turned on the strip of lights but when I run the on function from the web server that specific line doesn’t work. As stated before, I have extensively tested the on function to echo stuff like ls and everything and all of those tests have worked, just the command itself from the web server doesn’t work (yet the web server still activates the on function).

Anybody have any ideas?

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>LED Control</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<h1>LED CONTROL PANEL</h1>

<input type="submit" class="button" name="on" value="on" />
<input type="submit" class="button" name="off" value="off" />
<script>
$(document).ready(function(){
        $('.button').click(function(){
        var clickBtnValue = $(this).val();
        alert(clickBtnValue);
        var ajaxurl = 'ajax.php',
        data = {'action': clickBtnValue};
        $.post(ajaxurl, data, function (response){
        alert("Success");
        alert(response);
                });
        });
});
</script>

</body>
</html>

PHP Code:

<?php
        if(isset($_POST['action'])){
                switch ($_POST['action']) {
                        case 'on':
                                on();
                                break;
                        case 'off':
                                off();
                                break;
                }
        }
        function on() {
                echo exec("python LED/color.py");
                echo exec("ls LED");
                exit;
        }
        function off() {
                echo exec("python LED/off.py 'OFF'");
                exit;
        }
?>

UPDATE:
Updated the code in ajax.php and fixed the python script needing sudo yet it still does not work. The code works when executed in the directory of the ajax.php, and the ls does show that color.py is in LED.

How to&Answers:

i imagine it is waiting for you to type www-data password for sudo access … you should try and find a way to do this that does not require sudo

(I imagine you would have the same problem with exec('sudo ls'))