ftp_size
(PHP 4, PHP 5)
ftp_size — Возвращает размер файла
Описание
int ftp_size
( resource $ftp_stream
, string $remote_file
)
ftp_size() возвращает размер заданного файла в байтах.
Замечание: Не все FTP серверы поддерживают эту возможность.
Список параметров
- ftp_stream
-
Идентификатор соединения с FTP сервером
- remote_file
-
Имя файла на сервере
Возвращаемые значения
Возвращает размер файла, или -1 при возникновении ошибки.
Примеры
Пример #1 Пример использования ftp_size()
<?php
$file = 'somefile.txt';
// установка соединения
$conn_id = ftp_connect($ftp_server);
// проверка имени пользователя и пароля
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// получение размера файла $file
$res = ftp_size($conn_id, $file);
if ($res != -1) {
echo "Рамер файла $file $res байт";
} else {
echo "Не удалось определить размер файла $file";
}
// закрытие соединения
ftp_close($conn_id);
?>
- ftp_alloc
- ftp_cdup
- ftp_chdir
- ftp_chmod
- ftp_close
- ftp_connect
- ftp_delete
- ftp_exec
- ftp_fget
- ftp_fput
- ftp_get_option
- ftp_get
- ftp_login
- ftp_mdtm
- ftp_mkdir
- ftp_nb_continue
- ftp_nb_fget
- ftp_nb_fput
- ftp_nb_get
- ftp_nb_put
- ftp_nlist
- ftp_pasv
- ftp_put
- ftp_pwd
- ftp_quit
- ftp_raw
- ftp_rawlist
- ftp_rename
- ftp_rmdir
- ftp_set_option
- ftp_site
- ftp_size
- ftp_ssl_connect
- ftp_systype
Коментарии
$file= 'filename with space.txt';
$size = ftp_size($this->ftp, urldecode($file) );
this one can correctly return the size
otherwize, it always return -1
This will return the filesize on remote host and the size if you download it in FTP_BINARY mode. If you are using FTP_ASCII in ftp_get() the size can be changed.
Just to let people out there know, on my windows 2000 server running Apache and php i was returned 0 not -1 for directories.
foreach ($dir_list as $item)
{
if(ftp_size($conn_id, $item) == "0")
{
echo "<br>Directory:: ".$item;
} else {
echo "<br>File:: ".$item;
}
}
This outputs a list of the remote directory and indicates which items are directories and which are files.
To get a dirsize recursive you can use this simple function:
<?php # copyright by fackelkind | codeMaster
function getRecDirSize ($connection, $dir){
$temp = ftp_rawlist ($connection, "-alR $dir");
foreach ($temp as $file){
if (ereg ("([-d][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file, $regs)){
$isdir = (substr ($regs[1],0,1) == "d");
if (!$isdir)
$size += $regs[5];
}
}
return $size;
}
$dirSize = getRecDirSize ($conID, "/");
?>
Well this function is nice but if you have files larger then 2.1Gb or 2.1 Billion Bytes you cannot get its size.
note that project_t4 at hotmail dot com's example above doesn't work in general, though it works on his Win2K/Apache server; as far as I can tell there is no way to check over ftp whether a directory exists. This function's behavior given a directory name seems to be at least somewhat dependent on your OS, web server, or ftp server, I don't know which.
For checking if a certain folder exists try using ftp_nlist() function to get a directory list in array. By using in_array('foldername') you can find out if it is there or not.
2 adams[AT]techweavers[DOT]net:
To get a size of large file (f. ex.: 3.2 Gb) you have to format the result returned by ftp_size():
$size = sprintf ("%u", ftp_size($connection, $file_name));
So you can get the real size of big files. But this method is not good for checking is this a dir (when ftp_size() returns -1).
To overcome the 2GB file size limit, you can open your own socket to get the file size of a large file. Quick and dirty script:
<?php
$socket=fsockopen($hostName, 21);
$t=fgets($socket, 128);
fwrite($socket, "USER $myLogin\r\n");
$t=fgets($socket, 128);
fwrite($socket, "PASS $myPass\r\n");
$t=fgets($socket, 128);
fwrite($socket, "SIZE $fileName\r\n");
$t=fgets($socket, 128);
$fileSize=floatval(str_replace("213 ","",$t));
echo $fileSize;
fwrite($socket, "QUIT\r\n");
fclose($socket);
?>
If you experience troubles with size of large file then you can use ftp_rawlist function and parse it result
To overcome the 2 GB limitation, the ftp_raw solution below is probably the nicest. You can also perform this command using regular FTP commands:
<?php
$response = ftp_raw($ftpConnection, "SIZE $filename");
$filesize = floatval(str_replace('213 ', '', $response[0]));
?>
[However, this] is insufficient for use on directories. As per RFC 3659 (http://tools.ietf.org/html/rfc3659#section-4.2), servers should return error 550 (File not found) if the command is issued on something else than a file, or if some other error occurred. For example, Filezilla indeed returns this string when using the ftp_raw command on a directory:
array(1) {
[0]=>
string(18) "550 File not found"
}
RFC 959 (http://tools.ietf.org/html/rfc959) dictates that the returned string always consists of exactly 3 digits, followed by 1 space, followed by some text. (Multi-line text is allowed, but I am ignoring that.) So it is probably better to split the string with substr, or even a regular expression.
<?php
$response = ftp_raw($ftp, "SIZE $filename");
$responseCode = substr($response[0], 0, 3);
$responseMessage = substr($response[0], 4);
?>
Or with a regular expression:
<?php
$response = ftp_raw($ftp, "SIZE $filename");
if (preg_match("/^(\\d{3}) (.*)$/", $response[0], $matches) == 0)
throw new Exception("Unable to parse FTP reply: ".$response[0]);
list($response, $responseCode, $responseMessage) = $matches;
?>
You could then decide to assume that response code '550' means that it's a directory. I guess that's just as 'dangerous' as assuming that ftp_size -1 means that it's a directory.