2015-08-15 59 views
0

我有遠程服務器上的用戶文件夾(頁面文件除外)。我需要檢查整個「示例」文件夾的大小,而不是一個文件。我認爲我應該使用ftp來做,但我不能。遠程文件夾的PHP檢查大小

我有這樣的事情,但不工作:

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,我能做些什麼來解決這個問題?

+0

檢查這個http://stackoverflow.com/questions/478121/php-get-directory-size –

+0

http://stackoverflow.com/questions/2788002/i-want-get-the-sum-of -files-size-in-folder-by-php –

+0

沒錯,但我需要連接到另一個託管服務器。我編輯我的問題我添加了一個php代碼 – American

回答

1

在您的評論中,您表示您在遠程服務器上擁有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 /路徑/到/目錄,其中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'); 
+0

謝謝,這是否是另一種方式(沒有ssh2)? – American

+0

你可以在遠程服務器上運行php腳本嗎? –

+0

是的,我可以訪問兩個服務器(管理面板和ftp)。 – American