up vote 1 down vote favorite
share [g+] share [fb]

Why is the following not working.

<?php
$directory = './';
exec('ls -loh '.$directory, $directory_list);
echo '<ul>';
foreach($directory_list as $file){
var $x = explode(' ',$file);
echo '<li>'.$x[3].'</li>'; 
}
echo '</ul>';
?>

If i do not explode and i just do echo '<li>'.$file.'</li>'; then i get a string like this per li drwxr-xr-x 10 user 4.0K Sep 8 16:06 _test

I"m trying to get only the size and not the whole string. What am i doing wrong.

link|improve this question

are you splitting your string by double space – gowri Oct 7 '11 at 4:06
I'm using single space. – Pinkie Oct 7 '11 at 4:08
2  
You are aware that PHP has filesystem functions, aren't you – NullUserException Oct 7 '11 at 4:11
what result u u getting for now? – sicKo Oct 7 '11 at 7:53
feedback

3 Answers

up vote 1 down vote accepted

If you just want to get the sizes of the file,try this:

exec("ls -sh ./", $results);
foreach(array_slice($results,1,count($results)) as $file) {
    echo $file . "\n";
}

Here's my output:

4.0K 24
   0 BookingTest.php
   0 date
4.0K date.php
4.0K exec2.php
4.0K somefile
4.0K file.php
4.0K file
link|improve this answer
Great, it works. – Pinkie Oct 7 '11 at 8:48
feedback

I wouldn't say that you are doing something wrong - your approach is perfectly acceptable. However, if you want to avoid the explode() you could do something like:

<?php
$directory = './';
exec('ls -loh | awk \'{print $4}\''.$directory, $directory_list);
echo '<ul>';
foreach($directory_list as $file_size){

   echo '<li>'.$file_size.'</li>'; 
}
echo '</ul>';
?>
link|improve this answer
feedback

You can also use PHP for that:

$files = glob("./*");
$files = array_combine($files, array_map("filesize", $files));

Which gives you a nice associative array like:

[./curl.php] => 1499
[./db.php] => 10267
link|improve this answer
Thanks, That works perfectly, but i wanted to know why exec was not working. – Pinkie Oct 7 '11 at 8:47
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.