2

I'm tring to pass a string to a batch file from php using proc_open() on Windows. It works fine unless the string I'm passing is multiline, because it breaks the command with the line break. I tried various escaping methods, but none of them seems to work:

cmd style - prints the escape symbol and breaks line:

proc_open('script.bat -m "this is ^\n multiline"', $desc, $pipes)

another try - prints the whole string:

proc_open('script.bat -m "this is ^\\n multiline"', $desc, $pipes)

powershell style - prints the whole string:

proc_open('script.bat -m "this is `n multiline"', $desc, $pipes)

No matter what I tried, it either breaks the string anyway, or prints it as is, with no line break.

What am I missing or doing wrong? How to get multiline arguments to work via proc_open()?

René Beneš
  • 448
  • 1
  • 13
  • 29
  • Looks like you are missing an apostrophe - ' after the " before the , so for example the first one should be: proc_open('script.bat -m "this is ^\n multiline"', $desc, $pipes); you are opening an apostrophe ' string in all of your tries but not closing it.... – Shlomtzion Oct 05 '21 at 11:17
  • @Shlomtzion I'm sorry, my mistake when trying to reproduce the problem. I edited the question. However it doesn't relate to the point of the question, as I have it fine in my actual script. – René Beneš Oct 05 '21 at 11:20
  • In the powershell example you are not missing the ' - apostrophe ... that is probably why it works there.... – Shlomtzion Oct 05 '21 at 11:20
  • @Shlomtzion I have the closing apostrophe in my actual script. This was just my mistake while writing an example for sake of this question. – René Beneš Oct 05 '21 at 11:21
  • hmm, it sounds like something that urlencode will solve, there is a way to urldecode string within a batch file...I am really spitting balls here :) I have no idea if it will work. but if you want to try: https://stackoverflow.com/questions/28221685/urldecode-in-batch-file – Shlomtzion Oct 05 '21 at 11:26
  • As of PHP 7.4, the first parameter to [`proc_open`](https://www.php.net/manual/en/function.proc-open.php) can be an array of command parameters, and PHP will handle the escaping for you. I can guarantee it will solve your problem, but I’d try that. – Chris Haas Oct 05 '21 at 11:43

1 Answers1

0

Even if you get it escaped properly, it's nearly impossible, that your batch file is able to fetch a multi line argument.

You should test the batch script on it's own directly from cmd.exe, before trying to fix the escaping in php

c:\> script.bat This_is_^
More? 
More? multiline

A simple echo %* or set "arg=%~1" is not able to handle multi line arguments, but some hacks like:
How to receive even the strangest command line parameters?
Im passing a multi line text as argument which will ... has only 1 line

jeb
  • 78,592
  • 17
  • 171
  • 225