tags:

views:

23

answers:

4

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 php. If somehow i can "tell" php to "exec" from the usual environment. Any help would be appreciated.

+1  A: 

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)

Piskvor
+1  A: 

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.

Sjoerd
Your suggestion is also correct.. but i guess i can mark only 1 correct.. :)
Uday
+1  A: 

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

tweber
Hey ur solution works.. i tried with php AND command line.. Both output were same.. it WILL be the same but i had to be sure..
Uday
A: 

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.

D.Shawley
i m not sure abt the code but yeah thanks for the LANG part. My php runs in an environment where the LANG is "c" and the command line LANG is "en_US.UTF-8" which is why the difference..
Uday