Mox Mox - 3 months ago 23
PHP Question

how to pass string containing newline to python in php

I have the following line of code in php that I m using to execute the python screen. and it takes in text from a html textarea which will contain newline characters

$string = $_POST['textarea']; // e.g. "String 1\n string 2\n"
$command = escapeshellcmd("python script.py -c \"$string\"");


when the script.py is executed, only "String 1" is received by the python script as arg. May I ask is there any native way for me to get the string passed?

If you feel that this is a duplicated question, please let me know where I can find this answer. I have been searching it all over stackoverflow.

Mox Mox
Answer

I have managed to find a way to do this.

In the php file, replace all the newline with '\n' before calling escapeshellcmd

$string = trim(preg_replace('/[\r\n]+/', '\n', $_POST['textarea']));

// For a string like:
// abcd
// defg
// will become
// abde\\ndefg

Since the newline char '\n' has been escaped by php escapeshellcmd with the prepended slash. the shell will be able to process the string and python will receive abde\ndefg as one of the arguments. Next in the python code, we simply have to undo the escape using the code below

arg = sys.argv[1].decode('string_escape')

I hope the above solution will be able to help those who are facing the similar issue as me. =)

Comments