Загрузка файла на сервер с помощью JavaScript и библиотеки JQuery. Загрузка файлов с помощью PHP Как загрузить файл php
Данная возможность позволяет загружать как текстовые, так и бинарные файлы. С помощью PHP-функций аутентификации и работы с файлами вы имеете полный контроль над тем, кому разрешено загружать файлы и что делать с файлом после его загрузки.
PHP способен получать загруженные файлы из любого браузера, совместимого со стандартом RFC-1867.
Также следует заметить, что PHP поддерживает загрузку файлов методом PUT, который используется в клиентах Netscape Composer и W3C Amaya . Для получения более детальной документации обратитесь к разделу поддержка метода PUT .
Пример #1 Форма для загрузки файлов
Страница для загрузки файлов может быть реализована при помощи специальной формы, которая выглядит примерно так:
В приведенном выше примере __URL__ необходимо заменить ссылкой на PHP-скрипт.
Скрытое поле MAX_FILE_SIZE (значение необходимо указывать в байтах) должно предшествовать полю для выбора файла, и его значение является максимально допустимым размером принимаемого файла в PHP. Рекомендуется всегда использовать эту переменную, так как она предотвращает тревожное ожидание пользователей при передаче огромных файлов, только для того, чтобы узнать, что файл слишком большой и передача фактически не состоялась. Имейте в виду, что обойти это ограничение на стороне браузера достаточно просто, следовательно, вы не должны полагаться на то, что все файлы большего размера будут блокированы при помощи этой возможности. Это по большей части удобная возможность для пользователей клиентской части вашего приложения. Однако настройки PHP (на сервере) касательно максимального размера обойти невозможно.
Замечание :
Также следует убедиться, что форма загрузки имеет атрибут enctype="multipart/form-data" , в противном случае загрузка файлов на сервер не произойдет.
Оригинальное имя файла на компьютере клиента.
$_FILES["userfile"]["type"]Mime-тип файла, в случае, если браузер предоставил такую информацию. В качестве примера можно привести "image/gif" . Этот mime-тип не проверяется на стороне PHP, так что не полагайтесь на его значение без проверки.
$_FILES["userfile"]["size"]Размер в байтах принятого файла.
$_FILES["userfile"]["tmp_name"]Временное имя, с которым принятый файл был сохранен на сервере.
$_FILES["userfile"]["error"]По окончанию работы скрипта, если загруженный файл не был переименован или перемещен, он будет автоматически удален из временной папки.
foreach ($_FILES
[
"pictures"
][
"error"
] as
$key
=>
$error
) {
if ($error
==
UPLOAD_ERR_OK
) {
$tmp_name
=
$_FILES
[
"pictures"
][
"tmp_name"
][
$key
];
// basename() может спасти от атак на файловую систему;
// может понадобиться дополнительная проверка/очистка имени файла
$name
=
basename
($_FILES
[
"pictures"
][
"name"
][
$key
]);
move_uploaded_file
($tmp_name
,
"data/
$name
"
);
}
}
?>
Полоса прогресса загрузки файлов может быть реализована с помощью "отслеживания прогресса загрузки файлов с помощью сессий ".
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
) {
);
}
$file -> moveTo ("/path/to/new/file" );
?>
10 years ago
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
=> Array
=> facepalm.jpg
=> image/jpeg
=> /tmp/phpn3FmFr
=> 0
=> 15476
)
=> Array
=>
=>
=>
=> 4
=>
)
and not this
Array
=> Array
=> facepalm.jpg
=>
)
=> Array
=> image/jpeg
=>
)
=> Array
=> /tmp/phpn3FmFr
=>
)
=> Array
=> 0
=> 4
)
=> Array
=> 15476
=> 0
)
Anyways, here is a fuller example than the sparce one in the documentation above:
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
.
"".
\n"
;
else
$errormsg
.=
"Could not move uploaded file ""
.
$tmp_name
.
"" to ""
.
$name
.
""
\n"
;
}
else
$errormsg
.=
"Upload error. ["
.
$error
.
"] on file ""
.
$name
.
""
\n"
;
}
?>
3 years ago
The documentation doesn"t have any details about how the HTML array feature formats the $_FILES array.
Example $_FILES array:
For single file -
Array
=> Array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
Multi-files with HTML array feature -
Array
=> Array
=> Array
=> sample-file.doc
=> sample-file.doc
)
=> Array
=> application/msword
=> application/msword
)
=> Array
=> /tmp/path/phpVGCDAJ
=> /tmp/path/phpVGCDAJ
)
=> Array
=> 0
=> 0
)
=> Array
=> 0
=> 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.
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
=> Array
=> Array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
=> Array
=> Array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
=> Array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
4 years ago
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.
10 years ago
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).
2 years ago
I have found it useful to re-order the multidimensional $_FILES array into a more intuitive format, as proposed by many other developers already.
Unfortunately, most of the proposed functions are not able to re-order the $_FILES array when it has more than 1 additional dimension.
Therefore, I would like to contribute the function below, which is capable of meeting the aforementioned requirement:
function
get_fixed_files
() {
$function
= function($files
,
$fixed_files
= array(),
$path
= array()) use (&
$function
) {
foreach ($files
as
$key
=>
$value
) {
$temp
=
$path
;
$temp
=
$key
;
If (is_array
($value
)) {
$fixed_files
=
$function
($value
,
$fixed_files
,
$temp
);
} else {
$next
=
array_splice
($temp
,
1
,
1
);
$temp
=
array_merge
($temp
,
$next
);
$new = & $fixed_files ;
Foreach ($temp
as
$key
) {
$new
= &
$new
[
$key
];
}
$new
=
$value
;
}
}
Return
$fixed_files
;
};
Return
$function
($_FILES
);
}
?>
Side note: the unnamed function within the function is used to avoid confusion regarding the arguments necessary for the recursion within the function, for example when viewing the function in an IDE.
Приложение для загрузки файлов на сервер представляет собой HTML-форму (upload.html) и скрипт upload.php для ее обработки.
Замечание: Вы можете загрузить промышленную версию системы загрузки файлов на сервер из раздела . Система позволит вам не только загрузить файл на сервер, но и изменить его размер, фон и др.
Код формы (upload.html)
Форма для загрузки файлов