How to filter user' s input ( html, with PHP backend) with python?
Question: There is a web application written in PHP and HTML. What I want is to filter a
users input for a variety of cases and sanitize it. For example, I want to
compare the input from a form (string) with a list of allowed strings and
depending if it is right or wrong to trigger the suitable PHP function to
handle this.

My question is how to bind the user input with the python script and then the
outcome of this python script as an input for PHP?

thanks


Answer: You can call the Python script from your PHP file as a shell command, passing
it JSON-formatted arguments. Then have the Python script output the response
(also JSON encoded) and have the PHP file capture that. Here's an example I
used recently, cobbled together from the links below:

**PHP file:**

    
    
    $py_input = ... // Your data goes here.
    // Call the Python script, passing it the JSON argument, and capturing the result.
    $py_output = shell_exec('python script.py ' . escapeshellarg(json_encode($py_input)));
    $py_result = json_decode($py_output);
    

**Python file:**

    
    
    import json
    
    php_input = json.loads(sys.argv[1])  # The first command line argument.
    # Do your thing.
    php_output = ... # Whatever your output is.
    print json.dumps(php_output) # Print it out in JSON format.
    

[Passing a Python list to
php](http://stackoverflow.com/questions/17235467/passing-a-python-list-to-php)

[executing Python script in PHP and exchanging data between the
two](http://stackoverflow.com/questions/14047979/executing-python-script-in-
php-and-exchanging-data-between-the-two)

