Reputation: 37
I have a user folder on remote server (other than page files). I need check a size of whole "example" folder, not one file. I think i should do it with use a ftp, but I can't.
I have something like this but not working:
function dirFTPSize($ftpStream, $dir) {
$size = 0;
$files = ftp_nlist($ftpStream, $dir);
foreach ($files as $remoteFile) {
if(preg_match('/.*\/\.\.$/', $remoteFile) || preg_match('/.*\/\.$/', $remoteFile)){
continue;
}
$sizeTemp = ftp_size($ftpStream, $remoteFile);
if ($sizeTemp > 0) {
$size += $sizeTemp;
}elseif($sizeTemp == -1){//directorio
$size += dirFTPSize($ftpStream, $remoteFile);
}
}
return $size;
}
$hostname = '127.0.0.1';
$username = 'username';
$password = 'password';
$startdir = '/public_html'; // absolute path
$files = array();
$ftpStream = ftp_connect($hostname);
$login = ftp_login($ftpStream, $username, $password);
if (!$ftpStream) {
echo 'Wrong server!';
exit;
} else if (!$login) {
echo 'Wrong username/password!';
exit;
} else {
$size = dirFTPSize($ftpStream, $startdir);
}
echo number_format(($size / 1024 / 1024), 2, '.', '') . ' MB';
ftp_close($ftpStream);
Whole time script displays 0.00 MB, what can I do to fix it?
Upvotes: 1
Views: 2129
Reputation: 965
In your comments you indicated you have SSH access on the remote server. Great!
Here is a way to use SSH:
//connect to remote server (hostname, port)
$connection = ssh2_connect('www.example.com', 22);
//authenticate
ssh2_auth_password($connection, 'username', 'password');
//execute remote command (replace /path/to/directory with absolute path)
$stream = ssh2_exec($connection, 'du -s /path/to/directory');
stream_set_blocking($stream, true);
//get the output
$dirSize = stream_get_contents($stream);
//show the output and close the connection
echo $dirSize;
fclose($stream);
This will echo 123456 /path/to/directory where 123456 is the calculated size of the directory's contents. If you need human readable, you could use 'du -ch /path/to/directory | grep total' as the command, this will output formatted (k, M or G).
If you get an error "undefined function ssh2_connect()" you need to install/enable PHP ssh2 module on your local machine
Another way, without SSH could be to run the command on the remote machine. Create a new file on the remote server, e.g. called 'dirsize.php' with the following code:
<?php
$path = '/path/to/directory';
$output = exec('du -s ' . $path);
echo trim(str_replace($path, '', $output));
(or any other PHP code that can determine the size of a local directory's contents)
And on your local machine include in your code:
$dirsize = file_get_contents('http://www.example.com/dirsize.php');
Upvotes: 1