- PHP File Upload
- Configure The «php.ini» File
- Create The HTML Form
- Create The Upload File PHP Script
- Check if File Already Exists
- Limit File Size
- Limit File Type
- Complete Upload File PHP Script
- Complete PHP Filesystem Reference
- How to Upload Files with HTML
- How to Access Files
- How to Include a Request Body
- How to Set the Content-Type
- Recap
- Загрузка файлов
PHP File Upload
However, with ease comes danger, so always be careful when allowing file uploads!
Configure The «php.ini» File
First, ensure that PHP is configured to allow file uploads.
In your «php.ini» file, search for the file_uploads directive, and set it to On:
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
Some rules to follow for the HTML form above:
- Make sure that the form uses method=»post»
- The form also needs the following attribute: enctype=»multipart/form-data». It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
- The type=»file» attribute of the tag shows the input field as a file-select control, with a «Browse» button next to the input control
The form above sends data to a file called «upload.php», which we will create next.
Create The Upload File PHP Script
The «upload.php» file contains the code for uploading a file:
$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>
?>?php
- $target_dir = «uploads/» — specifies the directory where the file is going to be placed
- $target_file specifies the path of the file to be uploaded
- $uploadOk=1 is not used yet (will be used later)
- $imageFileType holds the file extension of the file (in lower case)
- Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called «uploads» in the directory where «upload.php» file resides. The uploaded files will be saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the «uploads» folder. If it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>
Limit File Size
The file input field in our HTML form above is named «fileToUpload».
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:
Complete Upload File PHP Script
The complete «upload.php» file now looks like this:
$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
?php
// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>
// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>
// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) echo «Sorry, your file was not uploaded.»;
// if everything is ok, try to upload file
> else if (move_uploaded_file($_FILES[«fileToUpload»][«tmp_name»], $target_file)) echo «The file «. htmlspecialchars( basename( $_FILES[«fileToUpload»][«name»])). » has been uploaded.»;
> else echo «Sorry, there was an error uploading your file.»;
>
>
?>
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
How to Upload Files with HTML
Austin Gil
When building applications with HTML, you may eventually come to a point where you need to allow users to upload files. Surprisingly, it’s not quite as straightforward as you might assume.
In this post, we’ll look at all things you need to support file uploads in HTML.
How to Access Files
The very first step is accessing a file to upload. Unfortunately, or rather, fortunately, browsers can’t access our file systems. If they did, it would be a major security concern.
There is work being done on the File System Access API, but it’s experimental and will be limited access, so let’s just pretend it doesn’t exist.
Accessing a file requires user interaction, which means we need something in the UI for the user to interact with. Conveniently, there is the input element with a file type attribute.
On its own, a file input isn’t very useful. It allows a user to select a file from their device, but that’s about it.
To actually send the file to a server, we need to make an HTTP request, which means we need a . We’ll put the file input inside along with a to submit the form.
The input will also need a to make it accessible for assistive technology, an id attribute to associate it with the label, and a name attribute in order to include its data along with the HTTP request.
How to Include a Request Body
If we watch the network tab as we submit the form, we can see that it generates a GET request, and the payload is sent as a query string that looks like this: “ ?name=filename.txt ”. It’s essentially a key-value pair, with the key being the input name and the value being the name of the file.
Not quite what we’re going for here.
We can’t actually send a file using a GET request because you can’t put a file in the query string parameters. We need to put the file in the body of the request.
To do that, we need to send a POST request, which we can do by changing the form’s method attribute to «post» .
Now, if we explore that request, we can see that we are making a post request. We can also see that the request has a payload containing the form’s data. Unfortunately, the data is still just a key-value pair with the input name and the filename.
How to Set the Content-Type
We’re still not actually sending the file, and the reason has to do with the request “ Content-Type ”.
By default, when a form is submitted, the request is sent with a Content-Type of application/x-www-form-urlencoded . And unfortunately, we can’t send the binary file information as URL encoded data.
In order to send the file contents as binary data, we have to change the Content-Type of the request to multipart/form-data . And in order to do that, we can set the form’s enctype attribute.
Now, if we submit the form one more time, we can see the request uses the POST method and has the Content-Type set to multipart/form-data . In Chromium browsers, you’ll no longer see the request payload, but you can see it in the Firefox DevTools under the request Params tab.
Recap
With all that in place, we can upload files using HTML. To re-iterate, sending files with HTML requires three things:
- Create an input with the type of file to access the file system.
- Use a form with method=»post» to include a body on the request.
- Set the request’s Content-Type to multipart/form-data using the enctype attribute.
Thank you so much for reading. If you liked this article, and want to support me, the best ways to do so are to share it, sign up for my newsletter, and follow me on Twitter.
Austin Gil
For over ten years I helped organizations build fast, secure, accessible websites. Now I help others do the same through high-quality content, open-source projects, and presentations.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Загрузка файлов
Для загрузки на сервер одного или нескольких файлов вроде фотографий, документов и видео применяется специальное поле формы. В браузере IE такой элемент отображается как текстовое поле, рядом с которым располагается кнопка с надписью «Обзор. » (рис. 1). В Safari, Opera и Chrome доступна только кнопка «Выбрать файлы» (рис. 2), в Firefox это только кнопка «Обзор» (рис. 3).
Рис. 1. Вид поля для загрузки файла в IE
Рис. 2. Загрузка файлов в Opera и Chrome
Рис. 3. Загрузка файлов в Firefox
При нажатии на кнопку открывается окно для выбора файла, где можно указать, какой файл пользователь желает использовать.
Синтаксис поля для отправки файла следующий.
Атрибуты перечислены в табл. 1.
Атрибут | Описание |
---|---|
name | Имя поля; используется для его идентификации обработчиком формы. |
disabled | Блокирует поле для отправки файлов. |
form | Идентификатор формы для связывания поля с элементом . |
type | Для загрузки файлов значение должно быть file . |
accept | Устанавливает фильтр на типы файлов, которые вы можете открыть через поле загрузки файлов. |
autofocus | Поле получает фокус после загрузки документа. |
required | Указывает, что поле является обязательным для заполнения. |
multiple | Позволяет выбирать и загружать сразу несколько файлов. |
Для отправки файлов в форме необходимо сделать следующее:
- задать метод отправки данных POST ( method=»post» );
- установить у атрибута enctype значение multipart/form-data .
Кроме того, данное поле нельзя вставлять внутрь ссылки и кнопки.
Форма для загрузки файла продемонстрирована в примере 1.
Пример 1. Создание поля для отправки файла
Атрибут multiple важен, он позволяет не ограничиваться одним файлом для выбора, а указать сразу несколько файлов для одновременной загрузки (пример 2). Выбор нескольких файлов происходит с помощью мыши или клавиатуры через клавиши Ctrl и Shift .
Пример 2. Загрузка нескольких файлов
Если атрибут accept не указывать, тогда добавляются и загружаются файлы любого типа. Наличие accept позволяет ограничить выбор файла, что особенно важно, когда требуется загрузить только изображение или видео. В качестве значения выступает MIME-тип, несколько значений разделяются между собой запятой. Также можно использовать следующие ключевые слова:
- audio/* — выбор музыкальных файлов любого типа;
- image/* — графические файлы;
- video/* — видеофайлы.
В табл. 2 показаны некоторые допустимые значения атрибута accept .
Значение | Описание |
---|---|
image/jpeg | Только файлы в формате JPEG. |
image/jpeg,image/png | Только файлы в формате JPEG и PNG. |
image/* | Любые графические файлы. |
image/*,video/* | Любые графические и видеофайлы. |
Использование дополнительных атрибутов показано в примере 3.
Пример 3. Загрузка фотографий