enedebe
enedebe

Reputation: 268

How to avoid "ls: write error: Broken pipe" with php exec

In PHP I am running this command:

exec ("ls -U ".$folder." |head -1000", $ls_u);

This command is inside a PHP file, run directly by PHP on the console and throws this error:

ls: write error: Broken pipe

What causes this error? Or is using pipes in PHP exec not a good idea?

Upvotes: 1

Views: 8390

Answers (2)

Eric Leschinski
Eric Leschinski

Reputation: 154063

In Linux with PHP on the terminal, you can reproduce this error with this code:

main.php:

<?php
  $process = popen("ls", "r");
  pclose($process);
?>

Then running it like this on the terminal:

eric@dev ~ $ php main.php
ls: write error: Broken pipe

The error happens because you are running a command which returns data and you are not catching it, so it complains about a broken pipe.

I was able to fix it like this:

<?php
  $handle = popen('ls', 'r');
  $read = fread($handle, 2096);
  pclose($handle);
  echo $read;
?>

Then it works, printing:

eric@dev ~ $ php main.php
main.php
anotherfile.txt

Note, you'll have to stick the fread(...) in a loop if you want to get all the output from ls.

Upvotes: 3

Samy Dindane
Samy Dindane

Reputation: 18716

I believe there's a syntax error in the console command, and suggest escaping the arguments with escapeshellarg().

exec('ls -U '.escapeshellarg($folder).' | head -1000', $ls_u);

Upvotes: -1

Related Questions