Загрузка файла на сервер и скачивание файла с сервера в PHP
С помощью PHP можно загружать файлы на сервер и скачивать файлы с сервера. То есть, с помощью PHP можно легко организовать хранилище файлов, галерею.
Разберём, как создать на PHP загрузчик файлов на сервер
Чтобы организовать загрузку файла на сервер в PHP скрипте, необходимо использовать multipart-форму с полем ввода типа file. В атрибуте формы enctype необходимо указать multipart/form-data
Общий вид формы загрузки файла в PHP
<form name="form" enctype="multipart/form-data" method="post">
<input type="file" name="upload_file" title="Выберите файл"/> </br>
<input type="submit" value = "Загрузить файл" name="button" /></br>
</form>
Здесь используется поле ввода для файла input type="file" Использование этого поля отображает на веб странице форму загрузки файла. upload_file — это имя загружаемого файла.
При обработке формы вся информация о файле в PHP записывается в глобальный массив $_FILES Основные значения глобального массива $_FILES:
$_FILES['upload_file']['name'] — имя файла до его отправки на сервер
$_FILES['upload_file']['size'] — размер загруженного файла в байтах;
$_FILES['upload_file']['type'] — тип загруженного файла
$_FILES['upload_file']['tmp_name'] — имя загруженного файла во временном каталоге
$_FILES['upload_file']['error'] — Код ошибки, которая может возникнуть при загрузке файла.
Указываем путь, куда необходимо загрузить файл
$переменная файла = "путь".$_FILES['upload_file']['name'];
Перед загрузкой файла в указанную папку, для безопасности он сохраняется во временную директорию. Путь к временному файлу указан в глобальном массиве $_FILES['upload_file']['tmp_name']
Чтобы файл загрузить в нужную папку из временной директории, используем команду
move_uploaded_file($_FILES['upload_file']['tmp_name'], $переменная файла);
После загрузки файла делаем проверку на существование загружаемого файла и выводим информацию о загруженном файле.
if(isset($_FILES['upload_file']['name']))
<
echo "Загруженный файл: ".$_FILES['upload_file']['name']."</br>";
echo "Размер: ".$_FILES['upload_file']['size']."байт";
>
Полный PHP код скрипта загрузчика файла. Для примера загружается файл с именем itrobo.jpg, после загрузки файла выводится информация о загруженном файле и загруженный файл на веб страницу.
<html>
<head>
<title></title>
</head>
<body>
<form name="form" enctype="multipart/form-data" method="post">
<input type="file" name="upload_file" title="Выберите файл"/> </br>
</br>
<input type="submit" value = "Загрузить файл" name="button" /></br>
</form>
</body>
</html>
<?php
$file = "upload/".$_FILES['upload_file']['name'];
move_uploaded_file($_FILES['upload_file']['tmp_name'], $file);
if(isset($_FILES['upload_file']['name']))
<
echo "Загруженный файл: ".$_FILES['upload_file']['name']."</br>";
echo "Размер: ".$_FILES['upload_file']['size']."байт";
echo '<p><img src="upload/itrobo.jpg" width="200" height="200" alt="image"></p>';
>
?>
Пример вывода скрипта на веб страницу

Скачивание файла с сервера с помощью PHP
Чтобы скачать файл с сервера в PHP, используется следующая конструкция
$переменная файла = путь к файлу;
header('Content-Type: тип файла);
header('Content-Disposition: attachment; filename="имя файла"');
readfile($переменная файла);
Пример скачивания файла с сервера с помощью PHP
$file = 'upload/itrobo.jpg';
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="itrobo.jpg"');
Напишем пример PHP скрипта, который выводит на веб страницу изображение с кнопкой "Загрузить!". При нажатии на кнопку "Загрузить!", картинка скачивается с веб сервера на компьютер.
Скрипты, в которых идёт вызов команды "Header", необходимо сохранять в кодировке UTF-8 без BOM. Это можно сделать с помощью редактора Notepad++. PHP обработчик следует писать в самом начале страницы.
Создаём HTML форму с кнопкой "Загрузить!". Она нужна для того, чтобы загрузить PHP обработчик скачивания файлов. Размещаем изображение на веб странице.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
</head>
<body>
Тег для вывода изображения в форме. Подробнее о работе с формами в PHP
<p><img src="upload/itrobo.jpg" width="400" height="400" alt="itrobo"></p>
<form name="form1" method="post">
</br>
<input type="submit" name="info" value="Загрузить!"> </br>
</body>
</html>
Напишем PHP обработчик кнопки Если кнопка нажата, скачиваем файл
<?
if(isset($_POST['info'])) <
$file = 'upload/itrobo.jpg';
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="itrobo.jpg"');
readfile($file);
>
?>
Полный код PHP скрипта для скачивания файла с сервера

<?
if(isset($_POST['info'])) <
$file = 'upload/flower.jpg';
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="itrobo.jpg"');
readfile($file);
>
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
</head>
<body>
<p><img src="upload/itrobo.jpg" width="400" height="400" alt="icon"></p>
<form name="form1" method="post">
</br>
<input type="submit" name="info" value="Загрузить!"> </br>
</body>
</html>
Пример вывода скрипта на веб страницу
How to Download a File in PHP
It was previously mentioned that zip and exe files download automatically, without using PHP script. First, create an HTML file with the following code. Here, the four anchor elements are defined to download the four types of files. These file types include TEXT, ZIP, PDF, and JPG files.
Download.html
Output
The following dialog box will appear to download the file after clicking the zip file link. The user can then download the file or open the file in the archive manager.
If you click on the image file, the image will be opened automatically in the browser, as shown in the following output. You must save the file to make a copy of the image file in the local drive. In the same way, when you click on PDF and TEXT file links, the content of the file will be opened in the browser without downloading the file. The solution to this problem is to download the file forcibly using the built-in PHP readfile() function.

Download File Using readfile() Function
The readfile() function is used in PHP script to forcibly download any file of the current location, or the file with the file path. The syntax of this function is given below.
Syntax
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
This function can take three arguments. The first argument is mandatory, and the other two arguments are optional. The first argument, $filename, stores the filename or filename with the path that will download. The default value of the second parameter, $use_include_path, is false and will be set to true if the filename with the path is used in the first argument. The third argument, $context, is used to indicate the context stream resource. This function returns the number of bytes read from the file mentioned in the first argument. The uses of this function are shown in the following two examples.
Example 1: Download File with Filename
In this example, we will create an HTML file with the following code, where the file name will be passed as a parameter of the URL named path, and the value of this parameter will be passed to the PHP file named download.php.
download2.html
We will create the PHP file with the following code to download the file forcibly. Here, the isset() function is used to check whether the $_GET[‘path’] is defined. If the variable is defined, the file_exists() function is used to check whether the file exists in the server. Next, the header() function is used to set the necessary header information before using the readfile() function. The basename() function is used to retrieve the filename, and the filesize() function is used to read the size of the file in bytes, which will be shown in the opening dialog box to download the file. The flush() function is used to clear the output buffer. The readfile() function is used with the filename only, here.
download.php
if ( isset ( $_GET [ ‘path’ ] ) )
{
//Read the filename
$filename = $_GET [ ‘path’ ] ;
//Check the file exists or not
if ( file_exists ( $filename ) ) {
//Define header information
header ( ‘Content-Description: File Transfer’ ) ;
header ( ‘Content-Type: application/octet-stream’ ) ;
header ( "Cache-Control: no-cache, must-revalidate" ) ;
header ( "Expires: 0" ) ;
header ( ‘Content-Disposition: attachment; filename="’ . basename ( $filename ) . ‘"’ ) ;
header ( ‘Content-Length: ‘ . filesize ( $filename ) ) ;
header ( ‘Pragma: public’ ) ;
//Read the size of the file
readfile ( $filename ) ;
//Terminate from the script
die ( ) ;
}
else {
echo "File does not exist." ;
}
}
else
echo "Filename is not defined."
?>
Output
The following output will appear after clicking the download link of the image file. The file size of the rose.jpg image is 27.2 KB, as shown in the dialog box. You can download the file by selecting the Save File radio button and pressing the OK button.

Example 2: Download File with File Path
If the file exists at the given file location, the file path will be required to mention in the URL. In this example, we will create an HTML file with the following code, which will pass the filename with the file path:
download3.html
We will create a PHP file with the following code to download a file from the file path. The PHP code in the previous example will be slightly modified to download the file from the given path. The clearstatecache() function is used to clear the cache that was previously stored. Two arguments are used in the readfile() function.
download2.php
//Check the file path exists or not
if ( file_exists ( $url ) ) {
//Define header information
header ( ‘Content-Description: File Transfer’ ) ;
header ( ‘Content-Type: application/octet-stream’ ) ;
header ( ‘Content-Disposition: attachment; filename="’ . basename ( $url ) . ‘"’ ) ;
header ( ‘Content-Length: ‘ . filesize ( $url ) ) ;
header ( ‘Pragma: public’ ) ;
//Read the size of the file
readfile ( $url , true ) ;
//Terminate from the script
die ( ) ;
}
else {
echo "File path does not exist." ;
}
}
echo "File path is not defined."
Output
After the download link of the PDF file is clicked, the following output will appear.

Video Tutorial
Conclusion
This article provided a simple way to forcibly download any file using the PHP script, to help readers to add the download feature in their script.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
Работа с FTP в PHP
Протокол FTP – предназначен для передачи файлов на удаленный хост. В PHP функции для работы с FTP как правило всегда доступны и не требуется установка дополнительного расширения.
Как правило, при работе с FTP выполняются следующие действия:
- Соединение с удаленным FTP-сервером (функция ftp_connect ).
- Авторизация ( ftp_login ).
- Действия с файлами.
- Закрытие соединения ( ftp_close ).
Список директорий и файлов
Функция ftp_nlist ($ftp_stream, $directory) получает список имен файлов и директорий в виде массива, где $ftp_stream – идентификатор соединения с FTP-сервером, $directory – путь к директории (в примере переменная пуста – это соответствует домашней директории FTP-пользователя).
Результат:
Получить список с расширенной информацией поможет функция ftp_rawlist() .
Результат:
Для получения детальных данных о файлах в виде массива есть функция ftp_mlsd(), но она появилась в PHP 7 и не всегда работает, для более ранних версий PHP:
Результат:
Поверка наличия файла/директории
Специальных функций для проверки существования файлов и директорий нет, поэтому можно использовать следующие варианты:
Проверить наличие файла на FTP-сервере
Функция ftp_size() возвращает «-1» если файл не найден.
Поверить наличие директории
Функция ftp_chdir() изменяет текущую директорию на FTP-сервере, возвращает false в случае возникновения ошибки.
Размер файла/директории
Получить размер файла
Функция ftp_size() возвращает размер файла в байтах.
Получить размер FTP директории
К полученному результату можно применить функцию для конвертации байтов в килобайты и мегабайты.
Php как скачать файл с сервера
In this article, we will see how to download & save the file from the URL in PHP, & will also understand the different ways to implement it through the examples. There are many approaches to download a file from a URL, some of them are discussed below:
Using file_get_contents() function: The file_get_contents() function is used to read a file into a string. This function uses memory mapping techniques that are supported by the server and thus enhances the performance making it a preferred way of reading the contents of a file.
Syntax:
Example 1: This example illustrates the use of file_get_contents() function to read the file into a string.