Progress28.ru

IT Новости
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Ftp put php

PHP | функция ftp_put ()

Функция ftp_put () — это встроенная функция в PHP, которая используется для загрузки файлов на FTP-сервер.

Синтаксис:

Параметр: эта функция принимает пять параметров, как указано выше и описано ниже:

  • $ ftp_connection: обязательный параметр. Он указывает уже существующее FTP-соединение, используемое для загрузки файла.
  • $ remote_file_path: обязательный параметр. Он указывает путь на удаленном сервере, т.е. на FTP-сервере, на который загружается файл.
  • $ local_file_path: обязательный параметр. Он указывает путь к файлу, который должен быть загружен на FTP-сервер.
  • $ mode: обязательный параметр. Указывает режим передачи. Значения параметра — либо FTP_ASCII, либо FTP_BINARY.
  • $ start_position: это необязательный параметр. Он указывает позицию в удаленном файле, в которую нужно начать загрузку.

Возвращаемое значение: возвращает True в случае успеха или False в случае неудачи.

Замечания:

  • Эта функция доступна в PHP 4.0.0 и более новой версии.
  • Следующие примеры не могут быть запущены в онлайн-среде IDE. Поэтому попробуйте запустить на каком-нибудь хостинг-сервере PHP или локальном хосте с правильным именем ftp-сервера.

Ниже приведены примеры, иллюстрирующие использование функции ftp_put () в PHP:

Пример 1:

// Подключаемся к FTP серверу

// Использовать правильное имя пользователя ftp

// Использовать правильный пароль FTP, соответствующий
// к имени пользователя ftp

// Имя файла или путь для загрузки на FTP-сервер

// Установка ftp соединения

$ftp_connection = ftp_connect( $ftp_server )

or die ( «Could not connect to $ftp_server» );

echo «Successfully connected to the ftp server!» ;

// Вход в установленное соединение с

// ftp пароль пользователя

$login = ftp_login( $ftp_connection , $ftp_username , $ftp_userpass );

// Проверка успешности входа в систему

echo «
logged in successfully!» ;

if (ftp_put( $ftp_connection ,

«uploadedfile_name_in_server.txt» , $file , FTP_ASCII))

echo «
Uploaded successful $file.» ;

echo «
Error while uploading $file.» ;

echo «
login failed!» ;

if (ftp_close( $ftp_connection )) <

echo «
Connection closed Successfully!» ;

Выход:

Пример 2. Подключитесь к ftp-серверу, используя номер порта 21, а затем загрузите файл.

// Подключаемся к FTP серверу

// Использовать правильное имя пользователя ftp

// Использовать правильный пароль FTP, соответствующий
// к имени пользователя ftp

// Имя файла или путь для загрузки на FTP-сервер

// Установка ftp соединения

$ftp_connection = ftp_connect( $ftp_server , 21)

or die ( «Could not connect to $ftp_server» );

echo «Successfully connected to the ftp server!» ;

// Вход в установленное соединение с

// ftp пароль пользователя

$login = ftp_login( $ftp_connection ,

// Проверка успешности входа в систему

echo «
logged in successfully!» ;

if (ftp_put( $ftp_connection ,

«uploadedfile_name_in_server.txt» , $file , FTP_ASCII))

echo «
Uploaded successful $file.» ;

echo «
Error while uploading $file.» ;

echo «
login failed!» ;

// Эхо ftp_get_option ($ ftp_connection, 1);

if (ftp_close( $ftp_connection )) <

echo «
Connection closed Successfully!» ;

ftp_put

(PHP 4, PHP 5, PHP 7)

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

Описание

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

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

Идентификатор соединения с FTP-сервером.

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

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

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

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

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

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

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

ВерсияОписание
7.3.0Теперь параметр mode опционален. Раньше он был обязательным.

Примеры

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

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

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

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

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

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

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

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

User Contributed Notes 32 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 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();

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:

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:wampbinapacheApache[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:wampwwwkevtestftp_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.

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

Couldn’t connect to $ftp_server

«); // set up basic connection

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
?>

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 ^_^

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.

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.

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

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

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.

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.

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.

Читать еще:  Phpmyadmin foreign keys
Ссылка на основную публикацию
Adblock
detector