Devon Bessemer
Devon Bessemer

Reputation: 35357

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");

Upvotes: 0

Views: 1770

Answers (2)

Lux
Lux

Reputation: 1600

As @Devon said, popen/pclose are very useful here.

$scriptHandle = popen("./script.sh","w");
while(($line = fgets(STDIN)) !== false){
    fputs($scriptHandle,$line);
}
pclose($scriptHandle);

Alternatively, something along the lines of fputs($scriptHandle, file_get_contents("php://stdin")); might work in the place of a line-by-line approach for a smaller file.

Upvotes: 2

Devon Bessemer
Devon Bessemer

Reputation: 35357

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);

Upvotes: 3

Related Questions