views:

105

answers:

3

I'm trying to run shell command like this from php:

ls -a | grep mydir

But php only uses the first command. Is there any way to force php to pass the whole string to the shell?

(I don't care about the output)

A: 

shell_exec

Sjoerd
A: 

If you want the output from the command, then you probably want the popen() function instead:

http://php.net/manual/en/function.popen.php

sarnold
A: 

http://www.php.net/manual/en/function.proc-open.php

First open ls -a read the output, store it in a var, then open grep mydir write the output that you have stored from ls -a then read again the new output.

L.E.:

<?php
//ls -a | grep mydir

$proc_ls = proc_open("ls -a",
  array(
    array("pipe","r"), //stdin
    array("pipe","w"), //stdout
    array("pipe","w")  //stderr
  ),
  $pipes);

$output_ls = stream_get_contents($pipes[1]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$return_value_ls = proc_close($proc_ls);


$proc_grep = proc_open("grep mydir",
  array(
    array("pipe","r"), //stdin
    array("pipe","w"), //stdout
    array("pipe","w")  //stderr
  ),
  $pipes);

fwrite($pipes[0], $output_ls);
fclose($pipes[0]);  
$output_grep = stream_get_contents($pipes[1]);

fclose($pipes[1]);
fclose($pipes[2]);
$return_value_grep = proc_close($proc_grep);


print $output_grep;
?>
daniels