ftp_fget
ftp_fget() загружает файл remote_filename с FTP-сервера и записывает его в переданный файловый дескриптор.
Список параметров
Открытый файловый дескриптор, в который будут сохранены данные.
Режим передачи. Должен быть либо FTP_ASCII , либо FTP_BINARY .
Позиция начала загрузки в удалённом файле.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
8.1.0 | Параметр ftp теперь ожидает экземпляр FTP\Connection ; ранее ожидался ресурс (resource). |
7.3.0 | Теперь параметр mode опционален. Раньше он был обязательным. |
Примеры
Пример #1 Пример использования ftp_fget()
// путь к удалённому файлу
$remote_file = ‘somefile.txt’ ;
$local_file = ‘localfile.txt’ ;
// открываем файл для записи
$handle = fopen ( $local_file , ‘w’ );
// установка соединения
$ftp = ftp_connect ( $ftp_server );
// вход с именем пользователя и паролем
$login_result = ftp_login ( $ftp , $ftp_user_name , $ftp_user_pass );
// пытаемся скачать файл и сохранить его в $handle
if ( ftp_fget ( $ftp , $handle , $remote_file , FTP_ASCII , 0 )) echo «Произведена запись в $local_file \n» ;
> else echo «При скачивании $remote_file в $local_file произошла проблема\n» ;
>
// закрытие соединения и локального файла
ftp_close ( $ftp );
fclose ( $handle );
?>
Смотрите также
- ftp_get() — Скачивает файл с FTP-сервера
- ftp_nb_get() — Скачивает файл с FTP-сервера в асинхронном режиме и сохраняет его в локальный файл
- ftp_nb_fget() — Скачивает файл с FTP-сервера в асинхронном режиме и сохраняет его в предварительно открытом файле
User Contributed Notes 6 notes
Another ftp_get_contents approach, using a temperary stream handler. Returns file contents as string.
function ftp_get_contents ( $conn_id , $filename ,
//Create temp handler:
$tempHandle = fopen ( ‘php://temp’ , ‘r+’ );
//Get file from FTP assuming that it exists:
ftp_fget ( $conn_id , $tempHandle , $filename , FTP_ASCII , 0 ));
//Getting detailed stats to check filesize:
$fstats = fstat ( $tempHandle );
return fread ( $tempHandle , $fstats [ ‘size’ ]);
>
?>
/**
* Function returns contents via FTP connection and returns it as string (right version. )
*/
function ftp_get_contents ( $conn_id , $filename ) <
//Create temp handler:
$tempHandle = fopen ( ‘php://temp’ , ‘r+’ );
?php>
//Get file from FTP:
if (@ ftp_fget ( $conn_id , $tempHandle , $filename , FTP_ASCII , 0 )) <
rewind ( $tempHandle );
return stream_get_contents ( $tempHandle );
> else <
return false ;
>
>
?>
if you are using windows ftp-server with cp1251 encoding there are some troubles with russian «я» in filename\path.
php use telnet to connect ftp-server and there are special symbol with code 255 in telnet protocol. You can try use ftp_raw($connection, ‘OPTS UTF8 ON’); and work in utf-8 (if server provides it).
P.S. sorry for my bad english
You might need to use ftp_pasv() if you’re behind a firewall and receiving odd timeouts, file creation but now local data saving, etc.
I was in need to synchronize two folders on two separate servers, one is a Windows server, and the other is a Linux server. I created this short and sweet function to help me do this. PLEASE NOTICE: This will not copy folders, and probably will fail if remote folder contains anything else than files.
function sync_folders($host, $port, $username, $password, $remote_dir, $local_dir, $passive_mode = true) $conn_id = ftp_connect($host, $port);
if (!$conn_id) return false; # fail to connect
if (!ftp_login($conn_id, $username, $password)) < ftp_close($conn_id); return false; ># fail to login
ftp_pasv($conn_id, $passive_mode);
if (!ftp_chdir($conn_id, $remote_dir)) < ftp_close($conn_id); return false; ># fail to change dir
if (substr($local_dir, -1) != ‘/’) $local_dir .= ‘/’;
$list = ftp_nlist($conn_id, ‘.’);
sort($list);
foreach ($list as $file) if (!file_exists($local_dir . $file)) $is_copied = ftp_get($conn_id, $local_dir . $file, $file, FTP_BINARY);
>
>
ftp_close($conn_id);
return true;
>
If you suply only a filename to the second parameter of function the ftp_get will open a pointer to the local file creating it and write to it.It’s ok if your server dont execute for to mutch time and you dont get too many files but if you do it too many times the pointers created by ftp_get will not be closed and will end your opened files capacity at your server making it to do not open any more files until you restart it.
Php загрузка файлов от своего сервера
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
Anyways, here is a fuller example than the sparce one in the documentation above:
foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;
$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);
if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>
Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;
$request = ServerRequestFactory :: fromGlobals ();
if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>
$uploaded_files = $request -> getUploadedFiles ();
if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>
$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];
if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>
$file -> moveTo ( ‘/path/to/new/file’ );
The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature —
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.
function normalize_files_array ( $files = [])
foreach( $files as $index => $file )
if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>
foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>
?>
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)