Search code examples
phppopenpassthru

How to pass the content of a variable trough an external command in php?


I have a variable that contains a long string. (specifically it contains a few kilobytes of javascript-code)

I want to pass this string trough an external command, in this case a javascript-compressor, and capture the output of the external command (the compressed javascript) in php, assigning it to a variable.

I'm aware that there's classes for compressing javascript in php, but this is merely one example of a general problem.

originally we used:

$newvar = passthru("echo $oldvar | compressor");

This works for small strings, but is insecure. (if oldvar contains characters with special meaning to the shell, then anything could happen)

Escaping with escapeshellarg fixes that, but the solution breaks for longer strings, because of OS-limitations on maximum allowable argument-length.

I tried using popen("command" "w") and writing to the command - this works, but the output from the command silently disappears into the void.

Conceptually, I just want to do the equivalent of:

$newvar = external_command($oldvar);

Solution

  • Using the proc_open-function you can get handles to both stdout and stdin of the process and thus write your data to it and read the result.