Search code examples
phppipestdinshell-exec

Pipe stdin into a shell script through php


We have a command line php application that maintains special permissions and want to use it to relay piped data into a shell script.

I know that we can read STDIN with:

while(!feof(STDIN)){
    $line = fgets(STDIN);
}

But how can I redirect that STDIN into a shell script?

The STDIN is far too large to load into memory, so I can't do something like:

shell_exec("echo ".STDIN." | script.sh");

Solution

  • Using xenon's answer with popen seems to do the trick.

    // Open the process handle
    $ph = popen("./script.sh","w");
    // This puts it into the file line by line.
    while(($line = fgets(STDIN)) !== false){
        // Put in line from STDIN. (Note that you may have to use `$line . '\n'`. I don't know
        fputs($ph,$line);
    }
    pclose($ph);