Upload Files to FTP Server in PHP

Загрузка файлов на FTP-сервер с помощью PHP (для новичков)

Для того чтобы загрузить файл на FTP-сервер, вам нужна HTML форма, где можно разместить такие детали FTP-соединения, как те, что описаны ниже:

  • server – сервер, на который вы хотите загрузить файл;
  • username – имя пользователя, под которым происходит соединение с FTP сервером;
  • password – пароль пользователя для доступа к FTP-серверу;
  • path to server – путь к FTP-серверу, на который вы хотите загрузить свой файл;
  • user file – файл, который вы собираетесь загрузить на FTP-сервер.

Подсказка : если вы хотите предложить пользователям вашего веб-сайта форму, куда они смогут загружать свои файлы, вы должны взять информацию о FTP-сервере и путь к нему из файла конфигурации. В этой статье мы демонстрируем подробный пример того, как загружать файлы через FTP, со всеми деталями.

У нас будет POST форма и атрибут enctype со значением multipart/form-data , потому что на нашей форме есть файл. Пользовательская форма, в которую нужно будет заносить информацию, выглядит так:

  
Current server: Username: Password: Path on the Server: Select File to Upload:

Когда пользователь отправляет форму, мы должны собрать всю информацию, которую пользователь занес в форму, и затем загрузить файл на FTP-сервер:

//имя файла, который нужно загрузить $filep = $_FILES['userfile']['tmp_name']; $ftp_server = $_POST['server']; $ftp_user_name = $_POST['user']; $ftp_user_pass = $_POST['password']; $paths = $_POST['pathserver']; //имя файла на сервере после того, как вы его загрузите $name = $_FILES['userfile']['name'];

Чтобы загрузить файл, мы должны, прежде всего, установить подключение к FTP-серверу с помощью функции ftp_connect , задав в качестве параметра адрес FTP-сервера. Функция возвращает идентификатор соединения:

$conn_id = ftp_connect($ftp_server);

После соединения с сервером мы должны войти в учетную запись, используя функцию ftp_login , имеющую три входных параметра: идентификатор соединения, имя пользователя на FTP, пароль пользователя. Также нужно проверить, был ли вход осуществлен удачно:

Читайте также:  Парсер web страниц python

// входим при помощи логина и пароля $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // проверяем подключение if ((!$conn_id) || (!$login_result)) < echo "FTP connection has failed!"; echo "Attempted to connect to $ftp_server for user: $ftp_user_name"; exit; >else

После авторизации мы можем загрузить файл на сервер, а затем проверить, был ли он загружен корректно:

// загружаем файл $upload = ftp_put($conn_id, ‘public_html/’.$paths.’/’.$name, $filep, FTP_BINARY); // проверяем статус загрузки if (!$upload) < echo "Error: FTP upload has failed!"; >else

Для закрытия FTP-соединения мы используем функцию ftp_close , принимающую в качестве параметра идентификатор соединения:

Для загрузки больших файлов необходимо установить для сервера ограничение по времени, чтобы не завершить скрипт, пока выполняется загрузка:

Источник

Upload files to ftp in php

For those who dont want to deal with handling the connection once created, here is a simple class that allows you to call any ftp function as if it were an extended method. It automatically puts the ftp connection into the first argument slot (as all ftp functions require).

public function __construct ( $url ) <
$this -> conn = ftp_connect ( $url );
>

public function __call ( $func , $a ) <
if( strstr ( $func , ‘ftp_’ ) !== false && function_exists ( $func )) <
array_unshift ( $a , $this -> conn );
return call_user_func_array ( $func , $a );
>else <
// replace with your own error handler.
die( » $func is not a valid FTP function» );
>
>
>

// Example
$ftp = new ftp ( ‘ftp.example.com’ );
$ftp -> ftp_login ( ‘username’ , ‘password’ );
var_dump ( $ftp -> ftp_nlist ());
?>

Upload file to server via ftp.

$ftp_server = «» ;
$ftp_user_name = «» ;
$ftp_user_pass = «» ;
$file = «» ; //tobe uploaded
$remote_file = «» ;

// set up basic connection
$conn_id = ftp_connect ( $ftp_server );

// login with username and password
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass );

// upload a file
if ( ftp_put ( $conn_id , $remote_file , $file , FTP_ASCII )) <
echo «successfully uploaded $file \n» ;
exit;
> else <
echo «There was a problem while uploading $file \n» ;
exit;
>
// close the connection
ftp_close ( $conn_id );
?>

In example 2 above you may need to set the system to to use pasv to get a result ie:

$ftp = new ftp(‘ftp.example.com’);
$ftp->ftp_login(‘username’,’password’);
$ftp->ftp_pasv(TRUE);
var_dump($ftp->ftp_nlist());

syntax error in the above example, ftp_nlist requires a directory parameter:

$ftp->ftp_nlist(‘.’); // retrieve contents of current directory

Источник

How to Upload File to FTP Server using PHP

Hi, in today’s post we will see how to upload files to ftp server using php script. File management via FTP is an essential skill for a web developer. A good FTP client would handle FTP communication, upload and download files from FTP server efficiently. But at times you may want to do it programmatically. With PHP, the native FTP functions allow you to easily handle all kinds of file operations with ease. Uploading files using PHP FTP functions is almost similar to doing it with an FTP client. Come on, I’ll show you how to transfer files to the server through ftp protocol in php.

php file upload to ftp server

Connecting FTP Server with PHP:

When you work with FTP protocol, you must establish a client-server connection. To do this, you must first connect to the FTP server and then log on using the credentials.

The following are the two PHP functions you need for this step.

  • ftp_connect(ftp_host)
  • ftp_login(ftp_connection, ftp_username, ftp_password)

Note that you need permission to log in and upload files to ftp server. So make sure you have it first.

Once you are logged in to the ftp server, you can upload files using,

ftp_put(ftp_connection, remote_file, source_file, transfer_mode)

This will transfer the source file to the remote directory.

Once you finish uploading, close the FTP stream this way,

ftp_close(ftp_connection)

How to Upload Files to FTP Server with PHP?

Now we know all the required PHP functions for FTP file transfer. Here I have created a PHP demo where you can perform file upload through the FTP protocol.

STEP-1) Create File Upload Form:

Build a simple file upload form with a file input and a submit button.

index.php

       
Please Choose File to Upload

php ftp file upload form

STEP-2) PHP FTP Uploader:

Once the form has been submitted, the FTP upload script will transfer the file to the FTP server using PHP’s FTP functions we discussed earlier.

ftp_upload.php

 else header('Location: index.php'); > ?>

In the above script, the ftp_connect() and ftp_login() functions are used to establish the connection to the provided ftp host and log in with the ftp credentials.

After successful logon, the ftp_put() function transfers the local file to the remote directory on FTP server. The function returns true or false based on the upload process and the success or error message will be displayed accordingly.

Once the file transfer is completed, the ftp stream will be closed using the ftp_close() function.

That’s it! I hope you now understand better uploading files to the ftp server using php. Just make sure you have FTP access and use the right host name and credentials of the FTP server. If you find this tutorial useful, please share it on social networks 🙂

Источник

How To Upload File On The FTP Server Using PHP

In this article, we will see how to upload files on the FTP server using PHP. As we know there are many FTP functions in PHP but whenever you want to upload a file in FTP using PHP that time FTP put function is very useful. The primary purpose of an FTP server is to allow users to upload and download files.

So, let’s see FTP function, file upload in FTP, ftp_put function, how to upload file to FTP server in Linux, upload files on FTP server using laravel, laravel upload file to the remote server.

The ftp_put() function is an inbuilt function in PHP that is used to upload files to the FTP server.

ftp_put(ftp_conn, remote_file, local_file, mode, startpos);

ftp_conn — ftp_conn is a required parameter and it is used to specify the FTP connection.

remote_file — remote_file is a required parameter and it is used to specify the file path to the upload path.

local_file — local_file is a required parameter and it is used to specify the path of the file to upload.

mode — mode is an optional parameter and it is used to specify the transfer mode. It has 2 possible values: 1) FTP_ASCII 2) FTP_BINARY.

startpos — startpos is an optional parameter and it is used to specify the position in the remote file to start uploading to.

Now, we will see the upload local file to a file on the FTP server:

 else < echo "Error uploading $file."; >// close connection ftp_close($ftp_conn); ?>

You might also like :

  • Read Also: How To Use Sweetalert2 In Laravel
  • Read Also: How To Connect FTP Server Using PHP
  • Read Also: How To Validate URL In PHP With Regex
  • Read Also: How to Add and Delete Rows Dynamically using jQuery

Источник

Оцените статью