【问题标题】:Php check size of remote folderphp检查远程文件夹的大小
【发布时间】:2015-08-15 18:13:47
【问题描述】:

我在远程服务器上有一个用户文件夹(页面文件除外)。我需要检查整个“示例”文件夹的大小,而不是一个文件。我想我应该用 ftp 来做,但我不能。

我有类似的东西但不工作:

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);

整个时间脚本显示 0.00 MB,我该如何解决?

【问题讨论】:

标签: php ftp server


【解决方案1】:

在您的 cmets 中,您表明您在远程服务器上具有 SSH 访问权限。伟大的!

这是使用 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);

这将回显 123456 /path/to/directory,其中 123456 是目录内容的计算大小。如果你需要人类可读,你可以使用 'du -ch /path/to/directory | grep total' 作为命令,这将输出格式化(k、M 或 G)。

如果您收到错误“未定义函数 ssh2_connect()”,您需要在本地机器上安装/启用 PHP ssh2 模块

另一种不使用 SSH 的方法是在远程机器上运行命令。 在远程服务器上创建一个新文件,例如使用以下代码调用“dirsize.php”:

<?php
$path   = '/path/to/directory';
$output =  exec('du -s ' . $path);
echo trim(str_replace($path, '', $output));

(或任何其他可以确定本地目录内容大小的 PHP 代码)

并在您的本地机器上包含在您的代码中:

$dirsize = file_get_contents('http://www.example.com/dirsize.php');

【讨论】:

  • 谢谢,是其他方式吗(没有 ssh2)?
  • 可以在远程服务器上运行php脚本吗?
  • 是的,我可以访问两台服务器(管理面板和 ftp)。
  • 不幸的是,“exec() 出于安全考虑已被禁用”,但我更改了脚本,使用了 file_get_contents() 和我的其他函数,并且可以正常工作。
  • 当然,任何可以确定本地目录内容大小的 PHP 代码都可以在第二个选项中使用。我已经编辑了答案以使其更清楚。
猜你喜欢
  • 2013-05-15
  • 2018-03-23
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
相关资源
最近更新 更多