Receiving a file from the user (upload)

PHP „is able” to receive files from the user. This is done using a field of type „file” on the form and the relevant variables in the script receiving the data.


<form action = „file2.php” method = „POST” ENCTYPE = „multipart / form-data”>
<input type = „file” name = „file” /> <br/>
<input type = „submit” value = „Send file” />



$max_size = 1000 * 1000;
if (is_uploaded_file ($_ FILES [ ‚file’] [ ‚TMP_NAME’])) {
if ($_FILES [ ‚file’] [ ‚size’]> $ max_rozmiar) {
echo ‚Error! The file is too big ‚;
} else {
echo „File received. Initial name: ‚. $_ FILES [‚ file ‚] [‚ name ‚];
echo ‚<br/>’;
if (isset ($_ FILES [ ‚file’] [ ‚type’])) {
echo ‚type’. $_ FILES [ ‚file’] [‚type’]. ‚<br/>’;
move_uploaded_file ($_ FILES [ ‚file’] [ ‚TMP_NAME’]
$_SERVER [ ‚DOCUMENT_ROOT’]. ‚/foto /’.$_ FILES [‚ file ‚] [‚ name ‚]);
} else {
echo ‚Error in data transmission’;


In the example used was is_uploaded_file function (). It checks whether the specified file actually been received from the user – check this is important, because if poorly written script „burglar” will be able to read any file from the server to which the right to read a user is running as a web server.
In turn are used available information about the file. If all attempts is successful, the file is moved to its final location using the function move_uploaded_file (). Of course, if a file with the same name already exists, it will be overwritten, so you should first check with the function file_exists ().
Another danger is the possibility of adding a PHP script on the server containing a „dangerous instructions.” You can protect against this by checking the extension or type of file being transferred. If the file extension is .php (or other, which is processed by the web server as a PHP script), or the file type is different from the expected (for example, all non-image / gif or image / jpeg) file, you can either remove or change his extension .
To file can be moved to its final location, the destination directory must have appropriate access rights. Namely, the user is running as a web server must have write access to the directory. All the necessary information can be obtained from the server administrator, or searching for a directive User file /etc/httpd/httpd.conf.

Close Menu