2

Within a PHP environment I am trying to execute sift (a grep-like program) to return filenames if either of the two strings matches.

// To return filenames having either string1 OR string2.
<?php
$cmd='sift.exe -l --blocksize=5000000 -Q string1^|string2 dir';
exec ($cmd);
?>

I am guessing I am unable to pass the OR operator (^|) correctly.

For matching a single string it works fine:

// To return filenames having string1
<?php
$cmd='sift.exe -l --blocksize=5000000 -Q string1 dir';
exec ($cmd);
?>

Any advice please?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • Remember it is customary to upvote answers that helped you, and check the "accepted answer" checkmark for the answer that most directly solved your problem. – Bill Karwin Oct 30 '17 at 14:42

2 Answers2

1

The pipe symbol is being interpreted by the shell that executes your command. You either need to escape the pipe symbol, or quote the pattern argument.

Here are two solutions that work:

$cmd='sift.exe -l --blocksize=5000000 -Q string1^\|string2 dir';

$cmd="sift.exe -l --blocksize=5000000 -Q 'string1^|string2' dir";
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
1

As Bill Karwin pointed out you have to escape some characters in your command.

PHP has escapeshellcmd function to take care of that, so you code should look like:

$cmd = 'sift.exe -l --blocksize=5000000 -Q string1^|string2 dir';
$escapedCommand = escapeshellcmd($cmd);
exec ($escapedCommand);

Optionally you can use escapeshellarg function.

Look at this question to see what characters need to be escaped.

zstate
  • 1,995
  • 1
  • 18
  • 20