ashim
ashim

Reputation: 25570

php, proc_open how pass multiple arguments

I am writing php code which will work under *nix systems. I need to call a python script with 5 arguments inside php code. Some of arguments are user input so there could be any characters. I cannot figure out how pass arguments to a script. How would I separate arguments?. For example in this question you separate by end of line character, but in my arguments could be anything written by users. How to pass such arguments? any ideas?

EDIT: I have idea of putting escape character in each quotes symbols ' or " before passing arguments, on the other end I will get rid of escape character. Does json encoding do it?

Upvotes: 3

Views: 3687

Answers (2)

Barmar
Barmar

Reputation: 782130

The function you want is escapeshellcmd():

$arg1 = escapeshellarg($input1);
$arg2 = "foo";
$arg3 = escapeshellarg($input3);
$arg4 = "bar";
$arg5 = escapeshellarg("a string containing spaces and other *special* characters");
$proc = proc_open("python_prog $arg1 $arg2 $arg3 $arg4 $arg5", ...);

In the other thread, the program didn't take any arguments, the newlines were being used to separate items on standard input.

Upvotes: 3

Andreas
Andreas

Reputation: 1791

You're basically executing a command on the command prompt; you might want to familiarize yourself with a command prompt first.

Parameters are separated by spaces. So if your inputs have spaces in them, you have to put quotes around these inputs (I suggest single quotes; using a double quote will lead to environment variables being expanded, among other things).

So basically, you have to escape all the single quotes, line breaks, and carriage returns in your inputs, surround each of them with single quotes and append them to the command.

Warning: Security-wise, this whole thing is very problematic. If your escape mechanism is not bullet-proof, anyone would be able to execute a command on your server.

An alternate answer would be to write the inputs into a temporary file, and read from this file in your python script. If you have control over this script, I would strongly suggest you to do that.

Upvotes: 1

Related Questions