Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get output of optipng

Tags:

php

I'm using jpegoptim and optipng to optimize images from a php-script which is called in the browser. I'm doing this:

$s = exec('/myoptimizer/jpegoptim -m60 -o --strip-all /httpd/images/myimage.jpg');
print $s;

This works fine and outputs:

/httpd/images/myimage.jpg 600x90 24bit P JFIF [OK] 14572 --> 14542 bytes (0.21%), optimized. 

Now the same with optipng:

$s = exec('/myoptimizer/optipng -o7 -preserve -strip all /httpd/images/myimage.png /httpd/images/myimage.png', $aOutput, $ret);

var_dump($s);
var_dump($a);
var_dump($ret);

But:
$s is empty.
$a is empty array.
$ret is 0.

Doing the same command on the console, I get:

** Processing: /httpd/images/myimage.png
60x18 pixels, 4x8 bits/pixel, RGB+alpha
Input IDAT size = 2235 bytes
Input file size = 2292 bytes

Trying:
  zc = 9  zm = 9  zs = 0  f = 5         IDAT size = 2235
  zc = 9  zm = 8  zs = 0  f = 5         IDAT size = 2235
  zc = 8  zm = 9  zs = 0  f = 5         IDAT size = 2235
  zc = 8  zm = 8  zs = 0  f = 5         IDAT size = 2235

/httpd/images/myimage.png is already optimized.

And:

$s = exec('/myoptimizer/optipng -h', $aOutput, $ret);
print $s;

works.

How can I get the output in PHP? I tried shell_exec, passthru and system as well, but: No output at all.

like image 504
Werner Avatar asked Mar 09 '18 14:03

Werner


1 Answers

The 2nd argument of the exec() method captures the standard output of the executed command. In your case, optipng does not output it's result to the standard output BUT to the standard error. You can redirect the std error message to the std output by adding 2>&1 to the end of your executing program, in this case your code will look like this:

<?php
$imagePath = '/httpd/images/myimage.png';
$comand    = '/myoptimizer/optipng -o7 -preserve -strip all';

exec("$command $imagePath 2>&1", $outout);

var_dump($output);
like image 136
StR Avatar answered Sep 22 '22 15:09

StR