ls -ltr using PHP exec()
as the problem states.. when i do
exec("ls -ltr > output.txt 2>&1",$result,$status);
its different from the normal output. An extra column gets added. something like
-rw-r--r-- 1 apache apache 211 Jul 1 15:52 withoutsudo.txt
-rw-r--r-- 1 apache apache 0 Jul 1 15:53 withsudo.txt
where as when executed from the command prompt its like
-rw-r--r-- 1 apache apache 211 2010-07-01 15:52 withoutsudo.txt
-rw-r--r-- 1 apache apache 274 2010-07-01 15:53 withsudo.txt
-rw-r--r-- 1 apache apache 346 2010-07-01 15:55 sudominusu.txt
-rw-r--r-- 1 apache apache 414 2010-07-01 15:58 sudominusu.txt
See the difference. So in the first output , my usual awk '{print $8}' fails. I was facing the same problem with cron. But solved it by calling
./$HOME/.bashrc
in the script. But not happening using 开发者_StackOverflowphp. If somehow i can "tell" php to "exec" from the usual environment. Any help would be appreciated.
In your login shell, ls
is probably aliased so that it prints another date. This would be in your .basrc or .bash_profile.
Explicitly pass the --time-style=
option to ls
to ensure that it prints the date in the expected format when using PHP.
I guess you are only interested in the file names and you want to sort with reverse time. Try this:
ls -tr1 > output.txt 2>&1
You'll get a list with only the file names, so you don't need awk at all.
Another solution is to specify the time format with "--time-style iso". Have a look at the man page
That's not an extra output, that's a difference in formatting the date. Apparently you have a different locale set in PHP and in bash ("command prompt").
(in bash, running export LANG=C
or export LANG=en_US
gives the result with three-letter month name)
The output of ls
is heavily dependent on the environment (e.g., LANG
being the important variable here). Why not use a combination of scandir
, stat
, and krsort
?
function ls($dir_name) {
$finfo = array();
foreach (scandir($dir_name) as $file_name) {
$s = stat(join('/', array($dir_name,$file_name)));
$finfo[$file_name] = $s['mtime'];
}
krsort($finfo);
return array_keys($finfo);
}
This will be safer and a lot more efficient than shelling out to ls
. Not to mention that you get the benefit of being about to customize the sorting and filter the results in ways that are difficult to do inside of an exec
.
BTW: I am by no means a PHP expert, so the above snippet is likely to be incredibly unsafe and full of errors.
精彩评论