Search code examples
phpcommand-lineinputstreamimage-compression

Passing a file from command line to PHP stdin


I am using an image manipulation library in PHP called Intervention. It's a great library but doesn't quite have all the features I need, specifically lossless compression. There are command line tools that do this, but I want to do the processing on the fly and pass the data to the browser, not write the data to the file system.

I want to pull the file data the is supposed to go to a file to be fed straight to PHP, but I am not familiar enough with the command line to know how to "pipe" the data to PHP or how to get PHP to read the data. Maybe something like this:

use Intervention\Image\ImageManagerStatic as Image;

$data = exec('optipng image.png >tophp');

$image_data = fopen('php://stdin', 'r');

$img = Image::make($image_data);

//...do more stuff...

echo $img->response();

I know that obviously won't work, but is there a way to accomplish what I am trying to do?


Solution

  • For any command line tools that have the ability to return the image data to stdout, you can capture that using shell_exec. Then you can pass that data to Intervention. Otherwise, you could save the data to a tmp file, have PHP read the data and then delete the file.