1

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

1
  • Presumably the Python script fails to run. Check exec() manual page. Use the 2nd and 3rd optional parameters to debug. Commented Jul 23, 2018 at 14:24

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Used the option <?php exec("/usr/bin/python3 /var/www/python_test.py $input_val"); and it logged.
Glad I could help!
You should use escapeshellarg($input_val) to prevent code-injection.
-2

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);

1 Comment

When you post answers with links to resources with which you have an affiliation, you are expected to disclose that affiliation in the post. Please edit your answer to include your affiliation. Otherwise your post may be deleted. Please see How to not be a spammer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.