Не работает ftp put

ftp_put

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_put — Загружает файл на FTP-сервер

Описание

ftp_put() загружает локальный файл на FTP-сервер.

Список параметров

Путь к файлу на FTP-сервере.

Путь к локальному файлу.

Задаёт режим передачи. Может принимать значения FTP_ASCII или FTP_BINARY .

Задаёт позицию в удалённом файле, в которую начнётся загрузка

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Версия Описание
8.1.0 Параметр ftp теперь ожидает экземпляр FTP\Connection ; ранее ожидался ресурс (resource).
7.3.0 Теперь параметр mode опционален. Раньше он был обязательным.

Примеры

Пример #1 Пример использования ftp_put()

= ‘somefile.txt’ ;
$remote_file = ‘readme.txt’ ;

// установка соединения
$ftp = ftp_connect ( $ftp_server );

// проверка имени пользователя и пароля
$login_result = ftp_login ( $ftp , $ftp_user_name , $ftp_user_pass );

// загрузка файла
if ( ftp_put ( $ftp , $remote_file , $file , FTP_ASCII )) <
echo » $file успешно загружен на сервер\n» ;
> else <
echo «Не удалось загрузить $file на сервер\n» ;
>

// закрытие соединения
ftp_close ( $ftp );
?>

Смотрите также

  • ftp_pasv() — Включает или выключает пассивный режим
  • ftp_fput() — Загружает предварительно открытый файл на FTP-сервер
  • ftp_nb_fput() — Загружает предварительно открытый файл на FTP-сервер в асинхронном режиме
  • ftp_nb_put() — Загружает файл на FTP-сервер в асинхронном режиме

User Contributed Notes 33 notes

If when using ftp_put you get the one of the following errors:

Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection

Warning: ftp_put() [function.ftp-put]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

( $resource , true );
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did 😀

if you examine the first user submitted function, ftp_putAll, it will work only if you extract this line and its matching bracket.

if (!@ftp_chdir($conn_id, $dst_dir.»/».$file))

The function will have changed into that directory before having uploaded files to it. This alters your upload path and the system will try to upload into an essentially non-existent directory (duped at the end).

Hope this helps some of you.
Cheers.
Saeven

If you want to copy a whole directory tree (with subdiretories),
this function (ftp_copy) might be usefull. Tested with
php 4.2.2 and a Linux OS.

$src_dir = «/from»;
$dst_dir = «/to»;

ftp_copy($src_dir, $dst_dir);
.
ftp_close($conn_id)

if (!@ftp_chdir($conn_id, $dst_dir.»/».$file)) <

ftp_copy($src_dir.»/».$file, $dst_dir.»/».$file);
>
else <

$upload = ftp_put($conn_id, $dst_dir.»/».$file, $src_dir.»/».$file, FTP_BINARY);
>
>
>

If you are having timeouts uploading a file, even very small files, you might have a look at ftp_pasv()

And don’t forget to do it after your ftp_login();

Couldn’t connect to $ftp_server

«); // set up basic connection

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die(«

You do not have access to this ftp server!

«); // login with username and password, or give invalid user message

if ((!$conn_id) || (!$login_result)) < // check connection
// wont ever hit this, b/c of the die call on ftp_login
echo «

FTP connection has failed!
«;
echo «Attempted to connect to $ftp_server for user $ftp_user_name

«;
exit;
> else <
//echo «Connected to $ftp_server, for user $ftp_user_name
«;
>

$upload = ftp_put($conn_id, $destination_file.$name, $filename, FTP_BINARY); // upload the file
if (!$upload) < // check upload status
echo «

FTP upload of $filename has failed!

Uploading $name Completed Successfully!

«;
>
ftp_close($conn_id); // close the FTP stream
?>

The following is a fully tested function (based on a previous note) that recursively puts files from a source directory to a destination directory. See http://rufy.com/tech/archives/000026.html for more information.

NOTE: use full path name for the destination directory and the destination directory must already exist

If you get this error when trying to send data to server :
Warning: ftp_put() [function.ftp-put]: Unable to build data connection: Connection timed out.

Two solutions :
— Add the program httpd.exe in your exception list for external connexions of your firewall. Indeed, the FTP protocol open a new socket for data transfer. And this socket is opened from the server to the client (your computer). This program is located (for WAMP) in C:\wamp\bin\apache\Apache[version]\bin\
— Use the ftp_pasv() function to activate the passive mode. In this mode, it is the client who open the new socket to the server.

Got this cryptic error

Warning: ftp_put() [function.ftp-put]: ‘STOR’ not understood in
C:\wamp\www\kevtest\ftp_todays.php on line 48

Found the prob, you can’t put a path to the destination file
(even though I can do that in the dos ftp client. )

e.g. — this doesn’t work
ftp_put($conn, ‘/www/site/file.html’,’c:/wamp/www/site/file.html’,FTP_BINARY);

you have to put

( $conn , ‘/www/site/’ );
ftp_put ( $conn , ‘file.html’ , ‘c:/wamp/www/site/file.html’ , FTP_BINARY );
?>

I [had an error for which] ftp_pasv didnt solve the problem. Here’s why:

FTP uses 2 connections on different ports, one for connection/handshake and another for data transfer.
The problem was that the ftp-server (that php was connecting to) also used different IP-addresses for the different connections (say what!?).
Normally the firewall (csf) detects ftp-connections and allows them through but because of the different IP-adresses this didn’t work.

Solution:
1 angry mail to the ftp server owner.
Allowing the second IP in the firewall.

ftp_put() can display confusing warning messages as it returns one line of the remote server’s response which may be multi lined.

If you’re transferring large amounts of files note that some file systems only support up to 2000 files per directory. This had me stumped for a while.

Currently, there is no function that lets you specifiy the file’s contents as a string. However, there is ftp_fput(), which operates on an open file. Using this function in conjunction with tmpfile() lets you emulate this kind of function. (You could also use php://memory, but this breaks BC).

function ftp_fputs ( $ftp_stream , $remote_file , $contents , $mode , $startpos = 0 )
<
$tmp = tmpfile ();
fwrite ( $tmp , $contents );
rewind ( $tmp );
$result = ftp_fput ( $ftp_stream , $remote_file , $tmp , $mode , $startpos );
fclose ( $tmp );
return $result ;
>
?>

Here is a fix for the function from lucas at rufy dot com below that will recursively put files from a source directory to a destination directory. As written below, it won’t put a file in a directory that already exists, because the the destination is altered. So here is the corrected function that will allow it to work:

I spent some time debugging a silly problem:

In php >= 5, ftp_put() will apparently rewind to the start of the file regardless of the state you left it in before sending it to the $host.

I found this out because I wasn’t closing the file handle before using ftp_put(). Since I had just written to the file, the file pointer must have been located at the *bottom*.

I was sending a 0-byte file on php 4.2.2., but worked fine on php 5.

So, just a heads up, don’t forget to close those filehandles. Even though I was using the filename as the argument for ftp_put, it still needs to be closed.

I did not call rewind on the file handle, just fclose($file_h).

victor at nobel dot com dot br wrote that
the correct dirpath format excluded «/home/USER/» from the public path, but for my server, i had to use it in order to get my scripts to work.

it may be obvious to most but I’m positing that you cannot use the $_SERVER[‘DOCUMENT_ROOT’] path since FTP starts at your top-level and therefore bypasses (or just plain doesn’t recognize) most of the virtual server pathing.

I had a little trouble getting the ftp_put to work, because of that particular server. All variables and data parsed from the previous web form had to be retreived using $_POST, $_GET or $_FILES.

If you don’t know what you sent use phpinfo(); to display what the server thinks about your data.

so. when sending files using a form and PHP, make sure that all the data (text files etc. ) are retreived with $_POST, and files (smiley.png, compression.zip, etc. ) are retreived with $_FILES.

here’s what your start of a results.php file might look like:
= $_POST [ ‘name’ ]; //This will copy the text into a variable
$myFile = $_FILES [ ‘file_name’ ]; // This will make an array out of the file information that was stored.
?>

Now when it comes to transmitting that information.

//where you want to throw the file on the webserver (relative to your login dir)

$destination_file = $destination_path . «img.jpg» ;

//This will create a full path with the file on the end for you to use, I like splitting the variables like this in case I need to use on on their own or if I’m dynamically creating new folders.

$file = $myFile [ ‘tmp_name’ ];

//Converts the array into a new string containing the path name on the server where your file is.

$upload = ftp_put ( $conn_id , $destination_file , $file , FTP_BINARY ); // upload the file
if (! $upload ) < // check upload status
echo «FTP upload of $destination_file has failed!» ;
> else <
echo «Uploaded $file to $conn_id as $destination_file » ;
>
?>

hope this is usefull ^_^

This is an extremely trivial thing but one that had me stumped forever (well, until I decided to check the error logs and see the error). I had a large file (mysql backup of a huge forum) that was only partially being uploaded to a remote backup server. Couldn’t figure out why, until I realized that the max execution time was being hit since it was taking longer than 30 seconds to upload this file.

( 0 );
rest of the code here .
?>

That did the trick. It’s one of those dumb, trivial things, and if you’re having trouble like I, it may be something you overlooked.

In case you aren’t aware. Some web hosting services do NOT allow outbound ftp unless you have a dedicated server account. A «shared» hosting account often doesn’t have this capability.

So if you can’t get your ftp, curl, or ssh remote file transfer functions to work, check with the host service and ask. You may have to upgrade your account.

If you are moving files from one folder to another inside the same server, the «local file» field has to be indicated in a relative path according to the location of the script running the ftp_put() function.

For example, your function is running on: /public_html/do_ftp.php and you want to move /public_html/products.php to /public_html/backup/products.php

The correct way to build the function would be:

ftp_put($ftp_id, ‘/public_html/backup/products.php’, ‘products.php’, FTP_ASCII);

After having headaches for 2 days trying to make this function work using absolute paths in both fields, I finally found the right way to use it. I hope it helps someone. Excuse my english, it isn’t my native language.

I’ve seen two notes about a «ftp_copy» function but i think there’s a misinterpretation about what an «ftp_copy» function should do. For me , it should be something like an ftp_rename that would keep the orginal file and clone it somewhere else on the same ftp server, as for them they consider its purpose is to copy a local file to a distant ftp ..well .. as in FTP protocol there’s no such thing as an FTP COPY command anyway, i think you’re free to interpret it as you want.
So here’s my solution using ftp_put and ftp_get ..

// bool ftp_copy ( resource $ftp_stream , string $initialpath, string $newpath, string $imagename )
function ftp_copy ( $conn_distant , $pathftp , $pathftpimg , $img ) <
// on recupere l’image puis on la repose dans le nouveau folder
if( ftp_get ( $conn_distant , TEMPFOLDER . $img , $pathftp . ‘/’ . $img , FTP_BINARY )) <
if( ftp_put ( $conn_distant , $pathftpimg . ‘/’ . $img , TEMPFOLDER . $img , FTP_BINARY )) <
unlink ( TEMPFOLDER . $img ) ;
> else <
return false ;
>

Yet another recursive ftp_put.

* The parameters are similar to that of ftp_put, so if you need to copy a directory, just use ftp_put_dir(. ) instead of ftp_put(. ).
* Another advantage is that the remote directory doesn’t need to exist.
* Returns TRUE on success, FALSE on failure.
* Inspired by lucas at rufy dot com and webmaster at sweetphp dot com.

function ftp_put_dir ( $ftp , $remote_dirname , $local_dirname , $mode = FTP_BINARY ) <
$success = true ;

// If necessary, create the remote directory.
if (! ftp_nlist ( $ftp , $remote_dirname )) <
if ( ftp_mkdir ( $ftp , $remote_dirname ) === false ) <
$success = false ;
>
>

$dir = dir ( $local_dirname );
while ( $f = $dir -> read ()) <
if ( $f === ‘.’ || $f === ‘..’ ) <
continue;
>
$lf = $local_dirname . ‘/’ . $f ;
$rf = $remote_dirname . ‘/’ . $f ;

if ( is_dir ( $lf )) <
if (! ftp_put_dir ( $ftp , $rf , $lf , $mode )) <
$success = false ;
>
> else <
if (! ftp_put ( $ftp , $rf , $lf , $mode )) <
$success = false ;
>
>
>
$dir -> close ();

Источник

ftp_fput

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_fput — Загружает предварительно открытый файл на FTP-сервер

Описание

ftp_fput() загружает данные из файлового дескриптора в удалённый файл на FTP-сервере.

Список параметров

Путь к удалённому файлу.

Открытый файловый дескриптор локального файла. Чтение прекращается при достижении конца файла.

Режим передачи. Должен быть либо FTP_ASCII , либо FTP_BINARY .

Позиция начала загрузки в удалённом файле.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Версия Описание
8.1.0 Параметр ftp теперь ожидает экземпляр FTP\Connection ; ранее ожидался ресурс (resource).
7.3.0 Теперь параметр mode опционален. Раньше он был обязательным.

Примеры

Пример #1 Пример использования ftp_fput()

// открыть файл для чтения
$file = ‘somefile.txt’ ;
$fp = fopen ( $file , ‘r’ );

// установка соединения
$ftp = ftp_connect ( $ftp_server );

// вход с именем пользователя и паролем
$login_result = ftp_login ( $ftp , $ftp_user_name , $ftp_user_pass );

// попытка загрузки файла
if ( ftp_fput ( $ftp , $file , $fp , FTP_ASCII )) <
echo «Файл $file успешно загружен\n» ;
> else <
echo «При загрузке $file произошла проблема\n» ;
>

// закрываем соединение и дескриптор файла
ftp_close ( $ftp );
fclose ( $fp );

Смотрите также

  • ftp_put() — Загружает файл на FTP-сервер
  • ftp_nb_fput() — Загружает предварительно открытый файл на FTP-сервер в асинхронном режиме
  • ftp_nb_put() — Загружает файл на FTP-сервер в асинхронном режиме

User Contributed Notes 10 notes

For directly inserting content into a file on an FTP host, you could also create a string stream wich streams directly to the ftp_fput function.

This should create less overhead than first writing to any temp directories locally before streaming, as suggested here.

= «Your content goes here» ;
$stream = fopen ( ‘data://text/plain,’ . $string , ‘r’ );

ftp_fput ( $this -> connection , $pathTo , $stream , FTP_BINARY );

If when using fput you get the one of the following errors:

Warning: ftp_fput() [function.ftp-fput]: Opening ASCII mode data connection

Warning: ftp_fput() [function.ftp-fput]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

( $resource , true );
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did 😀

Make sure you chdir to remote directory before using ftp_put or else ftp_put will just return error that it cannot create file. After you do the chdir you should NOT pass the whole path of file to ftp_put but just basename (filename). See example for more info.

Example:
= ‘local_path/resources/js/test.js’ ;
$rempath = ‘resources/js/’ ;
$remFile = ‘test.js’ ;

ftp_chdir ( $this -> conn_id , $rempath );
ftp_put ( $this -> conn_id , $remFile , $locpath , FTP_BINARY );
?>

When you have your file contents as a string, create temporary stream and use that as a file handle.

= «This is a test file\nTesting 1,2,3..» ;

$tempHandle = fopen ( ‘php://temp’ , ‘r+’ );
fwrite ( $tempHandle , $contents );
rewind ( $tempHandle );

ftp_fput ( $this -> ftp , $filename , $tempHandle , FTP_ASCII );

This might be obvious to most of you, but make sure your stream isn’t write-only. It has to be able to read from your stream in order to upload its contents.

Took me a while trying to figure out why my uploaded file was 0B, and that was why.

Источник

Читайте также:  Морозилка бирюса как настроить температуру
Оцените статью