<
html
>
<
head
>
<
title
>
Select and upload multiple
files to the server
< /
title
>
< /
head
>
<
body
>
data is encoded as MIME data ->
<
form
action
=
"file_upload.php"
method
=
" POST "
enctype
=
" multipart / form-data " >
<
h2
> Upload Files < /
h2
>
<
p
>
Select files to upload:
used in our PHP script ->
<
input
type
=
"file"
name
=
"files []"
multiple >
<
br
> <
br
>
<
input
type
=
"submit"
name
=
"submit"
value
=
"Upload"
>
< /
p
>
< /
form
>
< /
body
>
< /
html
>
file_upload.phpfile_upload script .php will handle the file upload and display the upload status.
// Check if the form was submitted
if
(isset (
$_ POST
[
’submit’
])) {
// Configure upload directory and allowed file types
$upload_dir
=
’uploads’
.DIRECTORY_SEPARATOR;
$allowed_types
=
array
(
’jpg’
,
’png’
,
’ jpeg’
,
’gif’
);
// Determine the maximum size for files, i.e. 2 MB
$maxsize
= 2 * 1024 * 1024;
// Checks if the user has submitted an empty form
if
(!
empty
(
array_filter
(
$_ FILES
[
’ files’
] [
’name’
]))) {
// Loop over each file in the files []
foreach array
(
$_ FILES
[
’files’
] [
’tmp_name’
]
as
$key
= >
$value
) {
$file_tmpname
=
$_ FILES
[
’files’
] [
’tmp_name’
] [
$key
];
$file_name
=
$_ FILES
[
’files’
] [
’name’
] [
$key
];
$file_size
=
$_ FILES
[
’files’
] [
’size’
] [
$key
];
$file_ext
=
pathinfo
(
$file_name
, PATHINFO_EXTENSION);
// Set file upload path
$filepath
=
$upload_dir
.
$file_name
;
// Check if the file type is allowed
if
(in_array (
strtolower
(
$file_ext
),
$allowed_types
)) {
// Checking the file size is not more than 2 MB
if
(
$file_size
>
$maxsize
)
echo
" Error: File size is larger than the allowed limit. "
;
// If a file with the name already exists, add the time to
// before the name file to avoid overwriting the file
if
(
file_exists
(
$filepath
)) {
$filepath
=
$upload_dir
. time().
$file_name
;
if
(move_uploaded_file (
$file_tmpname
,
$filepath
)) {
echo
"{$file_name} successfully uploaded
"
;
}
else
{
echo
"Error uploading {$file_name}
"
;
}
}
else
{
if
(move_uploaded_file (
$file_tmpname
,
$filepath
)) {
echo
"{$file_name} successfully uploaded
"
;
}
else
{
echo
"Error uploading {$file_name}
"
;
}
}
}
else
{
// If file extension is invalid
echo
"Error uploading {$file_name} "
;
echo
"({$file_ext } file type is not allowed)
"
;
}
}
}
else
{
// If no files selected
echo
"No files selected. "
;
}
}
?>
Output: - Before uploading the file:
- After uploading the file: