php ftp send file

Отдаем файлы эффективно с помощью PHP

1. Используем readfile()

Метод хорош тем, что работает с коробки. Надо только написать свою функцию отправки файла (немного измененный пример из официальной документации):

Таким способом можно отправлять даже большие файлы, так как PHP будет читать файл и сразу отдавать его пользователю по частям. В документации четко сказано, что readfile() не должен создавать проблемы с памятью.

2. Читаем и отправляем файл вручную

Метод использует тот же Drupal при отправке файлов из приватной файловой системы (файлы недоступны напрямую по ссылкам):

3. Используем модуль веб сервера

3a. Apache

Модуль XSendFile позволяет с помощью специального заголовка передать отправку файла самому Apache. Существуют версии по Unix и Windows, под версии 2.0.*, 2.2.* и 2.4.*

В настройках хоста нужно включить перехват заголовка с помощью директивы:

Также можно указать белый список директорий, файлы в которых могут быть обработаны. Важно: если у Вас сервер на базе Windows путь должен включать букву диска в верхнем регистре.

Описание возможных опций на сайте разработчика: https://tn123.org/mod_xsendfile/

Пример отправки файла:

3b. Nginx

Nginx умеет отправлять файлы из коробки через специальный заголовок.

Для корректной работы нужно запретить доступ к папку напрямую через конфигурационный файл:

Пример отправки файла (файл должен находиться в директории /some/path/protected):

Источник

Работа с 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_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.

Источник

I have a pdf file on disk that i need to send to a user when they make a request to a php script, what is the best way of doing this?

php ftp send file. Смотреть фото php ftp send file. Смотреть картинку php ftp send file. Картинка про php ftp send file. Фото php ftp send file

4 Answers 4

Assuming that it’s on the server:

won’t work. This will make the client wait for a response forever. You need to define headers so that it works the intended way. See this example from the official PHP manual:

php ftp send file. Смотреть фото php ftp send file. Смотреть картинку php ftp send file. Картинка про php ftp send file. Фото php ftp send file

Here is what you need to send a file with PHP :

As Julian Reschke commented, the validated answer MAY work, but it’s full of useless headers. The content-type should be set to the real type of the file, or some browsers (especially mobile browsers) may not download it properly.

If you are using Apache or Lighty, then the «best» way to do this from a performance point of view, is to use the X-Sendfile header. See this tutorial: https://www.h3xed.com/programming/how-to-use-x-sendfile-with-php-apache

Ok, so I’m no expert at PHP, I can only take credit for putting together a few other snippets of PHP to achieve what i needed it to do, and i thought i had better post this solution up in a few forums which asked the same question but i could not get to work myself. There did not seem to be a solution anywhere so here it is. It works for me. Ok so first off i created the PDF form and added a button which then submits form. In the actions of this submit form, i told it to PDF the complete document. Then i gave it a URL link to a php page, such as mail_my_form.php Then i created a php form, and named it the same as above. mail_my_form.php One last thing is to create a folder called pdfs in the root of where this php code will go. (So if you put the php in a folder called email, then inside the folder of email, you need another folder called pdfs) Now what this script does is: Saves the PDF to the file name pdfs. Then it attaches the file to an email and sends it. Then it deletes the file from the folder pdfs to save space. (you could take out the delete function to save your forms on your FTP also if you wanted to.
Here it is.

Hope this helps some of you.

Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *