I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
[1] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] =>
)
)
and not this
Array
(
[name] => Array
(
[0] => facepalm.jpg
[1] =>
)
[type] => Array
(
[0] => image/jpeg
[1] =>
)
[tmp_name] => Array
(
[0] => /tmp/phpn3FmFr
[1] =>
)
[error] => Array
(
[0] => 0
[1] => 4
)
[size] => Array
(
[0] => 15476
[1] => 0
)
)
Anyways, here is a fuller example than the sparce one in the documentation above:
<?php
foreach ($_FILES["attachment"]["error"] as $key => $error)
{
$tmp_name = $_FILES["attachment"]["tmp_name"][$key];
if (!$tmp_name) continue;
$name = basename($_FILES["attachment"]["name"][$key]);
if ($error == UPLOAD_ERR_OK)
{
if ( move_uploaded_file($tmp_name, "/tmp/".$name) )
$uploaded_array[] .= "Uploaded file '".$name."'.<br/>\n";
else
$errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'<br/>\n";
}
else $errormsg .= "Upload error. [".$error."] on file '".$name."'<br/>\n";
}
?>POST метод за поставување
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
POST метод за поставување
Референца за `features.file-upload.post-method.php` со подобрена типографија и навигација.
POST метод за поставување
Оваа функција им овозможува на луѓето да поставуваат текстуални и бинарни датотеки. Со функциите за автентикација и манипулација со датотеки на PHP, имате целосна контрола врз тоа кој е дозволен за поставување и што ќе се направи со датотеката откако ќе биде поставена.
PHP е способен да прима поставувања на датотеки од кој било прелистувач што е во согласност со RFC-1867.
Забелешка: Поврзани конфигурации Забелешка
Погледнете исто така file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time директиви во php.ini
PHP исто така поддржува поставувања на датотеки со PUT-метод како што се користи од Netscape Composer и W3C Amaya клиенти. Погледнете го Поддршка за PUT метод за повеќе детали.
Пример #1 Формулар за поставување датотеки
Екран за поставување датотеки може да се изгради со создавање посебен формулар кој изгледа вака:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
На __URL__ во горниот пример треба да се замени и да упатува на PHP датотека.
На MAX_FILE_SIZE скриен елемент (измерен во бајти) мора да му претходи на полето за внесување датотека, а неговата вредност е максималната големина на датотеката прифатена од PHP. Овој елемент на формуларот секогаш треба да се користи бидејќи им заштедува на корисниците мака да чекаат голема датотека да се пренесе само за да откријат дека била преголема и трансферот не успеал. Имајте предвид: измамата на ова поставување на страната на прелистувачот е доста лесна, затоа никогаш не се потпирајте на блокирање датотеки со поголема големина од оваа функција. Тоа е само погодност за корисниците на клиентската страна на апликацијата. Поставките на PHP (на страната на серверот) за максимална големина, сепак, не можат да се измамат.
Забелешка:
Бидете сигурни дека вашиот формулар за поставување датотеки има атрибут
enctype="multipart/form-data"инаку поставувањето на датотеката нема да работи.
Глобалната $_FILES ќе ги содржи сите информации за поставената датотека. Неговата содржина од примерот на формуларот е следна. Имајте предвид дека ова претпоставува употреба на името за поставување датотека userfile, како што се користи во горниот пример на скрипта. Ова може да биде кое било име.
- $_FILES['userfile']['name']
-
Оригиналното име на датотеката на машината на клиентот.
- $_FILES['userfile']['type']
-
MIME типот на датотеката, ако прелистувачот ја обезбедил оваа информација. Пример би бил
"image/gif"Типот на датотеката, ако прелистувачот ја обезбедил оваа информација. Пример би бил - $_FILES['userfile']['size']
-
. Овој тип на податоци сепак не се проверува од PHP страната и затоа не ја земајте неговата вредност здраво за готово.
- $_FILES['userfile']['tmp_name']
-
Големината, во бајти, на прикачената датотека.
- $_FILES['userfile']['error']
-
На Привременото име на датотеката во кое прикачената датотека е зачувана на серверот. код за грешка
- $_FILES['userfile']['full_path']
-
поврзано со ова прикачување на датотека.
Целосната патека како што е поднесена од прелистувачот. Оваа вредност не секогаш содржи вистинска структура на директориуми и не може да се верува. Достапно од PHP 8.1.0. upload_tmp_dir директивата во php.iniДатотеките, по дифолт, ќе бидат зачувани во стандардната привремена директорија на серверот, освен ако не е дадена друга локација со TMPDIR . Стандардната директорија на серверот може да се промени со поставување на променливата на опкружувањето putenv() во опкружувањето во кое работи PHP. Поставувањето со
од скрипта на PHP нема да работи. Оваа променлива на опкружувањето исто така може да се користи за да се осигура дека други операции работат на прикачените датотеки.
Пример #2 Валидирање на прикачувања на датотеки is_uploaded_file() and move_uploaded_file() Види ги и записите за функцијата
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>за понатамошни информации. Следниот пример ќе го обработи прикачувањето на датотека што дошло од форма. $_FILES['userfile']['size'] PHP скриптата што прима прикачена датотека треба да ја имплементира секоја неопходна логика за да утврди што треба да се направи со прикачената датотека. Можете, на пример, да ја користите $_FILES['userfile']['type'] променливата за да ги отфрлите сите датотеки што се премногу мали или премногу големи. Можете да ја користите $_FILES['userfile']['error'] променливата за да ги отфрлите сите датотеки што не одговараат на одредени критериуми за тип, но користете ја оваа само како прва од серијата проверки, бидејќи оваа вредност е целосно под контрола на клиентот и не се проверува од PHP страната. Исто така, можете да користите и да ја планирате вашата логика споредкодови за грешки
Ако не е избрана датотека за поставување во вашата форма, PHP ќе врати $_FILES['userfile']['size'] како 0, и $_FILES['userfile']['tmp_name'] како ништо.
Датотеката ќе биде избришана од привремената директориум на крајот од барањето ако не е преместена или преименувана.
Пример #3 Поставување низа од датотеки
PHP поддржува HTML низа функција дури и со датотеки.
<form action="" method="post" enctype="multipart/form-data"> <p>Pictures: <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="submit" value="Send" /> </p> </form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
?>Лента за напредок при поставување датотеки може да се имплементира со користење на Напредок на поставувањето на сесијата.
Белешки од корисници 10 белешки
Do not use Coreywelch or Daevid's way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[x][y][z]">
<input type="submit">
</form>
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
GitHub:
https://github.com/zendframework/zend-diactoros
Example:
<?php
use Psr\Http\Message\UploadedFileInterface;
use Zend\Diactoros\ServerRequestFactory;
$request = ServerRequestFactory::fromGlobals();
if ($request->getMethod() !== 'POST') {
http_response_code(405);
exit('Use POST method.');
}
$uploaded_files = $request->getUploadedFiles();
if (
!isset($uploaded_files['files']['x']['y']['z']) ||
!$uploaded_files['files']['x']['y']['z'] instanceof UploadedFileInterface
) {
http_response_code(400);
exit('Invalid request body.');
}
$file = $uploaded_files['files']['x']['y']['z'];
if ($file->getError() !== UPLOAD_ERR_OK) {
http_response_code(400);
exit('File uploading failed.');
}
$file->moveTo('/path/to/new/file');
?>mpyw is right, PSR-7 is awesome but a little overkill for simple projects (in my opinion).
Here's an example of function that returns the file upload metadata in a (PSR-7 *like*) normalized tree. This function deals with whatever dimension of upload metadata.
I kept the code extremely simple, it doesn't validate anything in $_FILES, etc... AND MOST IMPORTANTLY, it calls array_walk_recursive in an *undefined behaviour* way!!!
You can test it against the examples of the PSR-7 spec ( https://www.php-fig.org/psr/psr-7/#16-uploaded-files ) and try to add your own checks that will detect the error in the last example ^^
<?php
/**
* THIS CODE IS ABSOLUTELY NOT MEANT FOR PRODUCTION !!! MAY ITS INSIGHTS HELP YOU !!!
*/
function getNormalizedFiles()
{
$normalized = array();
if ( isset($_FILES) ) {
foreach ( $_FILES as $field => $metadata ) {
$normalized[$field] = array(); // needs initialization for array_replace_recursive
foreach ( $metadata as $meta => $data ) { // $meta is 'tmp_name', 'error', etc...
if ( is_array($data) ) {
// insert the current meta just before each leaf !!! WRONG USE OF ARRAY_WALK_RECURSIVE !!!
array_walk_recursive($data, function (&$v,$k) use ($meta) { $v = array( $meta => $v ); });
// fuse the current metadata with the previous ones
$normalized[$field] = array_replace_recursive($normalized[$field], $data);
} else {
$normalized[$field][$meta] = $data;
}
}
}
}
return $normalized;
}
?>The documentation doesn't have any details about how the HTML array feature formats the $_FILES array.
Example $_FILES array:
For single file -
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature -
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
[type] => Array
(
[0] => application/msword
[1] => application/msword
)
[tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 0
[1] => 0
)
)
)
The problem occurs when you have a form that uses both single file and HTML array feature. The array isn't normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.
<?php
function normalize_files_array($files = []) {
$normalized_array = [];
foreach($files as $index => $file) {
if (!is_array($file['name'])) {
$normalized_array[$index][] = $file;
continue;
}
foreach($file['name'] as $idx => $name) {
$normalized_array[$index][$idx] = [
'name' => $name,
'type' => $file['type'][$idx],
'tmp_name' => $file['tmp_name'][$idx],
'error' => $file['error'][$idx],
'size' => $file['size'][$idx]
];
}
}
return $normalized_array;
}
?>
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
[1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
)For clarity; the reason you would NOT want to replace the example script with
$uploaddir = './';
is because if you have no coded file constraints a nerd could upload a php script with the same name of one of your scripts in the scripts directory.
Given the right settings and permissions php-cgi is capable of replacing even php files.
Imagine if it replaced the upload post processor file itself. The next "upload" could lead to some easy exploits.
Even when replacements are not possible; uploading an .htaccess file could cause some problems, especially if it is sent after the nerd throws in a devious script to use htaccess to redirect to his upload.
There are probably more ways of exploiting it. Don't let the nerds get you.
More sensible to use a fresh directory for uploads with some form of unique naming algorithm; maybe even a cron job for sanitizing the directory so older files do not linger for too long.Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side. You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client. This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini
post_max_size should be >= upload_max_filesize in your php.ini.Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.In object-oriented design, I believe that the methods of Coreywelch or Daevid are more correct. Their suggestions ensure the integrity of a single file object during multi-file uploads, and regardless of whether users upload multi-level file directories, they are only displayed in the full_path attribute. In fact, PHP associative arrays should be objects, while arrays should be keyless; otherwise, the boundary between objects and arrays becomes too blurred. PHP is still the most efficient web service language today and will inevitably move toward strong typing, rather than just being used to quickly write a bunch of code with unpredictable results, especially in the current era of AI popularity.
For example, an input that supports uploading a folder along with all its files or subfolders.
<input type="file" name="uploads[]" multiple webkitdirectory>
It aligns more with object-oriented design thinking, but it is still an associative array.
Array
(
[0] => Array
(
[name] => facepalm.jpg
[full_path] => User/Path/to/facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
[1] => Array
(
[name] =>
[full_path] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] =>
)
)
But in the end, it should be like this:
Object $userfile
$userfile->name // facepalm.jpg
$userfile->full_path // User/Path/to/facepalm.jpg
$userfile->type // image/jpeg
$userfile->tmp_name // /tmp/phpn3FmFr
$userfile->error // 0
$userfile->size // 15476It's not necessary to write multiple input fields in the form to upload multiple files, this way, with only one input also works:
<input type="file" name="nomfile[]" multiple>