• Uncategorized

About php : Case-Insensitive-Shell-Command-Not-Working-With-PHP-Exec

Question Detail

I am running PHP 7.0.22, under LAMP, on two ubuntu 16.04.

When I open a shell and type

ls -1 /var/www/dropbox/*.[Cc][Ee][Ll] >

it creates a file, /var/www/dropbox/temp.lst, listing all the files, in /var/www/dropbox, that end in .cel or .CEL.

However, when I run PHP code containing

    $str="ls -1 /var/www/dropbox/*.[Cc][Ee][Ll] >/var/www/dropbox/temp.lst";
    exec($str);

I do not get /var/www/dropbox/temp.lst created and /var/log/apache2/error.log contains the error message

ls: cannot access '/var/www/dropbox/*.[Cc][Ee][Ll]': No such file or directory

Edit 1:

    $str="ls -1 /var/www/dropbox/*.[Cc][Ee][Ll]";
    $results = explode(PHP_EOL, shell_exec($str));
    print_r($results);
    echo "<br>";

returns

Array ( [0] => ) 

Question Answer

You need shell_exec(), not exec(). You should also use egrep. Namely, ls | egrep '*.CEL|*.cel' Try using shell_exec($str). That will solve this issue.

exec() executes an external program.
shell_exec() executes a command via shell and returns the complete output as a string

It will return the results as a string.

<?php
$command = "ls | egrep '*.CEL|*.cel'";
$results = explode(PHP_EOL, shell_exec($command));
print_r($results);
?>

The results should be as follows

Array
(
    [0] => luminol.cel
    [1] => luminol.CEL
    [2] =>
)

Sources:
http://php.net/manual/en/function.shell-exec.php
http://php.net/manual/en/function.exec.php

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.