开发者

Getting the entire size of a website using php's FTP functions

开发者 https://www.devze.com 2023-03-05 21:23 出处:网络
I\'m trying to get the size of my website using php and ftp. I would like to get the size of everything under httpdocs, (files and directories combined)

I'm trying to get the size of my website using php and ftp. I would like to get the size of everything under httpdocs, (files and directories combined)

And have it output: My website is 42.5MB.

开发者_高级运维

I've tried ftp_rawlist, but that gives me an ugly array that I have no idea how to parse. (Im new to php arrays). It also only gives me the file sizes of the files under httpdocs, not files within directories in httpdocs.

Is there some sort of recursive function that will do this?


Figured it out.

Anyway, here is what I wrote up to get this working.

<?php
$host = 'HOST';
$username = 'USERNAME';
$password = 'PASSWORD';
$dir_is = 'DIRECTORY_TO_USE';
$conn_id = ftp_connect($host);
$login_result = ftp_login($conn_id, $username,$password);
$rawfiles = ftp_rawlist($conn_id, $dir_is, true);

$total_size = 0;
foreach($rawfiles as $info){
  $info = preg_split("/[\s]+/", $info, 9);
  $size = $info[4];
  $total_size += $size;
}

function convert_size($size, $decimals = 1) {
  $suffix = array('Bytes','KB','MB','GB','TB','PB','EB','ZB','YB','NB','DB');
  $i = 0;

  while ($size >= 1024 && ($i < count($suffix) - 1)){
    $size /= 1024;
    $i++;
  }
  return round($size, $decimals).' '.$suffix[$i];
}

echo 'Total Size is: '.convert_size($total_size); 

?>

Replace with your connection info:

$host = 'HOST';

$username = 'USERNAME';

$password = 'PASSWORD';

$dir_is = 'DIRECTORY_TO_USE';


Is there some sort of recursive function that will do this?

No, you have to write it yourself. If you are new to arrays it means you are completely new to php, since most of work there is done on arrays. You would need more string parsing here and here is general algorithm:

  1. Iterate through this array replacing every multiple whitespaces to single space
  2. Explode line with space, you will get new array
  3. Take first character of first element in new array
  4. If char is equal to '-' you have regular file - add 5th element (size) to global counter
  5. Else id char is equal to 'd' - it is directory. It's name is in the last element of new array - take it, open it and repeat from step one until you run out of files ;)
  6. Every other starting character such as 's' (socket) or 'l' (symbolic link) can be omitted since there are no regular files and their size is rather insignificant

This is a little walk-around version, proper would be to use sscanf to parse single line, but I think this one presented above is easier to understand for beginner

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号