Travis
Travis

Reputation: 687

PHP Execute Python Script on button click

I am using php to have a button refresh a python script. The goal of this is to when a certain input is present and a button is pressed, to run the python script. If there is no user input, there is a default value for $input_val, just incase. The way I have been trying to test this is in my python file, I have a line that should output to var/tmp/my_logfile.log, but no logs are being returned when run through the php page. Like every other stack article I've seen it works in the command prompt.

The code I use to try this has been the following:

PHP:

if (isset($_POST['update']))
{
    exec('/usr/bin/python3 /var/www/python_test.py ".$input_val."');
}

HTML:

<form name="update" method="post" >
    <button name = "update" type="submit"> Update charts </button>
</form>

Some of the references I have used, but to no luck:

Execute Python script from Php

HTML form button to run PHP to execute Python script

https://www.raspberrypi.org/forums/viewtopic.php?t=105932

https://serverfault.com/questions/679198/executing-a-python-script-through-php-button

Upvotes: 1

Views: 8882

Answers (2)

Mahedi Hasan
Mahedi Hasan

Reputation: 1078

PHP's shell_exec() function or the more modern proc_open() can be used to run Python scripts.

Example: Running a Python Script from PHP

<?php

function runPythonScript(string $scriptPath): string {
    $output = shell_exec("python3 " . escapeshellarg($scriptPath));
    return $output ?: 'Error running Python script.';
}

echo runPythonScript('/path/to/your_script.py');

Here, PHP’s shell_exec() runs the Python script, and its output is returned to the PHP environment. It's essential to sanitize input before passing it to the shell to avoid injection vulnerabilities, which is why escapeshellarg() is used.

Example: Calling a Python API from PHP

Let's assume we have a Python web service running at http://localhost:5000 that returns some processed data:

Python (Flask) Example:

# app.py
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/process-data', methods=['GET'])
def process_data():
    result = {'message': 'Data processed successfully', 'status': 'OK'}
    return jsonify(result)

if __name__ == '__main__':
    app.run(port=5000)

Now, in PHP, we can use cURL to make a GET request to this Python service:

<?php

function callPythonApi(string $url): array {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true) ?? [];
}

$apiResponse = callPythonApi('http://localhost:5000/process-data');

print_r($apiResponse);

Read the complete blog of this article Bridging PHP and Python for Next-Level Development

Upvotes: -1

delboy1978uk
delboy1978uk

Reputation: 12365

You can't put a variable in a single quote string, unless that is what you actually want. Instead, either break out and concatenate, or use double quotes:

<?php exec('/usr/bin/python3 /var/www/python_test.py "' . $input_val . '"'); // note extra single quotes

Or:

<?php exec("/usr/bin/python3 /var/www/python_test.py \"$input_val\""); 

The above codes presume you actually type the double quotes in the terminal.

If not, just get rid of them like so:

<?php exec('/usr/bin/python3 /var/www/python_test.py ' . $input_val );

Or:

<?php exec("/usr/bin/python3 /var/www/python_test.py $input_val");

Upvotes: 3

Related Questions