Search code examples
phpdateformatexecls

ls output changing when used through exec()


I'm using the ls command via PHP and exec() and I get a different output than when I run the same command via the shell. When running ls through PHP the year and month of the date get changed into the month name:

Running the command through the shell:

$ ls -lh /path/to/file
 -rw-r--r-- 1 sysadmin sysadmin 36M 2011-05-18 13:25 file

Running the command via PHP:

<?php
exec("ls -lh /path/to/file", $output);
print_r($output);

/*
Array
(
    [0] => -rw-r--r-- 1 sysadmin sysadmin  36M May 18 13:25 file
)
*/

Please note that:
-the issue doesn't occur when I run the PHP script via the cli (it only occurs when run through apache)
-I checked the source code of the page to make sure that what I was seeing was what I was getting (and I do get the month name instead of the proper date)
-I also run the ls command through the shell as the www-data user to see if ls was giving different output depending on the user (the output is the always the same from the shell, that is I get the date in yyyy-mm-dd instead of the month name)

Update with answer

alias was giving me this:

alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'

From those aliases I was unable to find a switch that was directly responsible for the time display:

-C  list entries by columns
-F  append indicator (one of */=>@|) to entries
-A  do not list implied . and ..
-a  do not ignore entries starting with .
-l  use a long listing format

However using --time-style=long-iso in PHP did fix the issue.


Solution

  • ls has a couple command line options for date display format. check that your command line version isn't aliased to include something like ls --time-style=locale. The PHP exec'd version will most likely not have this aliasing present and is using default ls settings.