php ftp открыть файл
Работа с FTP через PHP
Иногда бывает нужно загрузить различные файлы по FTP через PHP. Например, можно подправить какой-нибудь движок, а затем определить все свежие файлы (по дате изменения) и загрузить их обратно на сервер. Таким образом, если движок большой, то не придётся ждать, пока загрузятся все файлы. Но это лишь пример того, как можно использовать FTP через PHP. А теперь давайте разберём, как это делается.
Разберём простой пример по работе с FTP через PHP:
Код хорошо прокомментирован, поэтому, что происходит, думаю, Вы понимаете. Безусловно, это лишь часть функций, самые важные. А с полным списком Вы можете ознакомиться в справочнике.
Не могу сказать, что я очень часто работаю с FTP через PHP, но уметь это необходимо любому разработчику, поэтому и написал эту статью.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 3 ):
привет,добавил сайт на хостинг,сайт на php.набрал в браузере адрес сайта,вместо сайта вышел html код станицы index.php.в чем здесь проблема?спасибо.
Так и должен был выйти HTML-код, а если помимо него выводится ещё и PHP, то проверьте: поддерживает ли хостинг PHP.
А почему XML-файлы передаются в бинарном режиме?
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
Работа с FTP средствами PHP
Протокол FTP (File Transfer Protocol — протокол передачи файлов) — один из старейших протоколов Интернета, предназначенный для передачи файлов между двумя хостами.
Как правило, при работе с FTP выполняются следующие стандартные действия:
соединение с удаленным FTP-сервером
регистрация на FTP-сервере
загрузка файлов с сервера или на сервер
закрытие соединения
Соединение с FTP-сервером
Соединение с удаленным FTP-сервером выполняется с помощью функции ftp_connect:
В качестве обязательного параметра эта функция принимает имя хоста host, с которым необходимо установить соединение. Второй необязательный параметр port указывает на номер порта, через который осуществляется соединение. Если этот параметр не указан, то соединение осуществляется через порт 21, являющийся стандартным FTP-портом. Третий необязательный параметр определяет максимально время выполнения сценария (тайм-аут) и по умолчанию равен 90 секундам.
Соединение с удаленным FTP-сервером
Регистрация на FTP-сервере
После того, как соединение установлено, необходимо зарегистрироваться на сервере с определенным именем и паролем. Сделать это можно при помощи функции ftp_login.
Как видно из листинга, функция ftp_login принимает три параметра: дескриптор FTP-соединения, возвращаемый функцией ftp_connect, имя пользователя и пароль.
Замечание: Регистрация на сервере не требуется, если FTP-сервер является анонимным.
Закрытие соединения
По окончании сеанса связи с FTP-сервером, нужно закрыть FTP-соединение с помощью функции ftp_quit, принимающей в качестве единственного параметра дескриптор FTP-соединения:
Загрузка файлов с сервера
Загрузка файлов с сервера осуществляется при помощи функции ftp_get:
Аргумент mode, задающий режим пересылки файлов, должен быть указан как константа FTP_BINARY или FTP_ASCII. Режим FTP_ASCII используется для пересылки файлов, состоящих только из ASCII-символов (т. е. текстовых файлов), а двоичный режим — для пересылки всех остальных файлов.
Переход в родительский каталог
Изменение текущего рабочего каталога на родительский производится с помощью функции ftp_cdup:
Изменение текущего рабочего каталога
Изменение текущего рабочего каталога на указанный осуществляется при помощи функции ftp_chdir:
Удаление файлов
Удалить файл с FTP-сервера можно с помощью функции ftp_delete:
Здесь ftp_connect — дескриптор соединения, а remote_file — имя удаляемого файла.
Создание каталога
Новый каталог можно создать, используя функцию ftp_mkdir:
Эта функция возвращает имя созданного каталога или false в случае неудачи:
Перечисление файлов в каталоге
Узнать, какие файлы находятся в текущем каталоге, можно применив функцию ftp_nlist:
ftp_get
(PHP 4, PHP 5, PHP 7, PHP 8)
ftp_get — Скачивает файл с FTP-сервера
Описание
ftp_get() загружает удалённый файл с FTP-сервера и сохраняет его локально.
Список параметров
Идентификатор соединения с FTP-сервером.
Путь к локальному файлу (файл будет перезаписан, если уже существует).
Путь к удалённому файлу.
Позиция начала загрузки в удалённом файле.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Теперь параметр mode опционален. Раньше он был обязательным. |
Примеры
Пример #1 Пример использования ftp_get()
// объявление переменных
$local_file = ‘local.zip’ ;
$server_file = ‘server.zip’ ;
Смотрите также
User Contributed Notes 18 notes
I tried to ftp a 7mb file today off my webserver.
I copied this example directly and it told me.
Port command successful
«there was a problem»
I thought it was because of the size.
But I guessed it might be cause of my firewall.
So I made the ftp connection passive:
?>
Ran the script again & it worked fine.
Hope this helps someone
Don’t want to use an intermediate file? Use ‘php://output’ as the filename and then capture the output using output buffering.
Here’s a quick function that figures out the correct mode to use based on a file’s extension.
ftp_sync is a way to walk the directory structure on the server and copy every directory and file to the same location locally.
ftp_sync ( «DirectoryToCopy» ); // Use «.» if you are in the current directory
If you ran the example and see that it fail after 90sec (timeout).
// define some variables
$folder_path = «YOUR FOLDER PATH» ;
$local_file = «LOCAL FILE PATH» ;
$server_file = «SERVER FILE PATH» ;
//— Connection Settings
$ftp_server = «IP ADDRESS» ; // Address of FTP server.
$ftp_user_name = «USERNAME» ; // Username
$ftp_user_pass = «PASSWORD» ; // Password
#$destination_file = «FILEPATH»;
If someone will try to download files to the same local file (some temporary file), like shown here:
If someone will think that problem is just in getting proper file size (which you will get using filssize() function) he will be mistaken. The download file’s size is not equal to source file’s size materially, that means fflush() function will not solve the problem (I have tried this as well).
Finally the solution was founded: before downloading a file you will need to delete local file if such exist (‘temp.tmp’). So working code will look like:
If you previously downloaded a file before (like a huge web log), and just want to get the remaining portion, do this:
This same code works regardless of wether the local file exists already or not. You should first test to make sure the local file is not bigger than the remote file.
On Windows (and possibly *NIX) you will get «[function.ftp-get]: failed to open stream: No such file or directory in. » errors if the local_file path contains directory paths that do not already exist.
Even with write permissions ftp_get can create the file but it will NOT automatically create the parent directories as you might expect.
I am running a Windows Server and the php script is running from C:/xampp/htdocs/file.php
I’d suggest use ftp_fget() instead of ftp_get() since the latter only return TRUE or FALSE and there’s no obvious way to get the cause of failure.
Using ftp_fget, you have to pass a file handle as local file, so you have to do fopen() first. By way of this, you can find ‘Permission Denied’ problem when call fopen(). If you use ftp_get(), there’s no way to find this error cause.
In my case, I run httpd using ‘nobody’ and I create ftp local folder using ‘haha’. It tooks me long time to find the ‘Permission Denied’ problem at that time since I use ftp_get() then.
Remember to use the full server paths to the directories you are working on. Server paths are not the same as «ftp paths».
I was using the path displayed on my FTP client to download and upload files and I kept getting «Not found» or «Permission Denied» errors.
ftp_fput
(PHP 4, PHP 5, PHP 7, PHP 8)
ftp_fput — Загружает предварительно открытый файл на FTP-сервер
Описание
ftp_fput() загружает данные из файлового дескриптора в удалённый файл на FTP-сервере.
Список параметров
Идентификатор соединения с FTP-сервером.
Путь к удалённому файлу.
Открытый файловый дескриптор локального файла. Чтение прекращается при достижении конца файла.
Позиция начала загрузки в удалённом файле.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Теперь параметр mode опционален. Раньше он был обязательным. |
Примеры
Пример #1 Пример использования ftp_fput()
Смотрите также
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.
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:
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’ ;
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..» ;
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.
ftp_put
(PHP 4, PHP 5, PHP 7, PHP 8)
ftp_put — Загружает файл на FTP-сервер
Описание
ftp_put() загружает локальный файл на FTP-сервер.
Список параметров
Идентификатор соединения с FTP-сервером.
Путь к файлу на FTP-сервере.
Путь к локальному файлу.
Задаёт позицию в удалённом файле, в которую начнётся загрузка
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Теперь параметр mode опционален. Раньше он был обязательным. |
Примеры
Пример #1 Пример использования ftp_put()
= ‘somefile.txt’ ;
$remote_file = ‘readme.txt’ ;
Смотрите также
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:
if you examine the first user submitted function, ftp_putAll, it will work only if you extract this line and its matching bracket.
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»;
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();
«); // 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_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. )
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).
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:
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.
If you don’t know what you sent use phpinfo(); to display what the server thinks about your data.
//where you want to throw the file on the webserver (relative to your login dir)
//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.
//Converts the array into a new string containing the path name on the server where your file is.
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.
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.
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.