Multipart forms
- Web interfaces of mail services that allow you to add an attachment (attach) to a letter, and to do 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 exchange files of various programs, etc.
Uploading a file to the server is carried out using a multipart form, which has a file upload field. The enctype parameter is set to multipart/form-data :
This is what the given multipart form will look like (you can try using it to see the result of the multipart forms by uploading a 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 ;
- Field for specifying the file name that it will have on the server .
Processing multipart forms
Before you start writing a script for processing a multipart form, you need to edit the configuration file php.ini to allow files to be uploaded to the server.
The PHP configuration file php.ini has three parameters related to uploading files to the server:
- file_uploads=On - allows files to be uploaded to the server via HTTP;
- 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 a Linux operating system, then you need to restart the service:
service httpd restart
How does PHP handle multipart forms? Once it receives the file, it saves it in a temporary directory called upload_tmp_dir , with the file name chosen at random. It then creates four superglobal array variables $_FILES . This array contains information about the downloaded file.
The variables defined for uploaded files depend on the PHP version and current configuration. The superglobal array $_FILES is available since PHP 4.1.0. In case the register_globals configuration directive is set to on, additionally variables with appropriate names will be declared. As of 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 this assumes the name uploadfile is used for the file selection field, as per the multipart form above. Of course, the field name can be anything.
- $_FILES["uploadfile"]["name"] - the name of the file 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 was able to detect it), for example: image/gif, image/png, image/jpeg, text/html;
- (that’s what we called the file upload field) - contains the name of the file in the temporary directory, for example: /tmp/phpV3b3qY;
- $_FILES["uploadfile"]["error"] - Error code that may occur when downloading a file. Key ["error"] was added in PHP 4.2.0. You can see the corresponding error codes
After the script completes, the temporary file will be deleted. This means that we must copy it to another location before the script completes. That is, the algorithm for the script to upload a file to the server is as follows:
If the "Submit" button is pressed, 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 a file named $_FILES["uploadfile"]["tmp_name"] to some directory (write rights to this directory are required).
The file is copied using the function copy() :
Only use the copy() copy function, not the move function, because:
- The temporary file will be deleted automatically;
- If the temporary directory is on other media, an error message will be displayed.
Let's say we need to upload a file to the uploads directory, which is located in the root directory of the web server (in the DocumentRoot directory).
// Let's create a directory just in case. If it has already been created,
// we won't see an error message because we'll use the @ operator:
@mkdir("uploads", 0777);
// Copy the file from /tmp to uploads
// The file name will be the same as before sending to the server:
Copy($_FILES["uploadfile"]["tmp_name"],"uploads/".basename($_FILES["uploadfile"]["name"]));
On Linux, everything is much more complicated - we need to take into account the permissions of the uploads directory. Most likely in this case, the function mkdir() won't work because we don't have write permission to the DocumentRoot directory (usually /var/www/html or /home/httpd/html). Log in as root, create an uploads directory, and change its owner and permissions as follows:
// Create the uploads directory
// Set the apache owner name and its group - also apache:
Chown apache:apache uploads
// Allow everyone to write (777) + set the sticky bit (1):
Chmod 1777 uploads
The file size can be limited; if desired, you can edit the .htaccess file and limit 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 for uploading files to the server
php Original name of the uploaded file: "
// 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 downloaded file:
echo "Information about the file uploaded to the server:
"
;
echo "
echo "
Mime type of the uploaded file: "
.$ _FILES [ "uploadfile" ][ "type" ]. "" ;echo "
Uploaded file size in bytes: "
.$ _FILES [ "uploadfile" ][ "size" ]. "" ;echo "
Temporary file name: "
.$ _FILES [ "uploadfile" ][ "tmp_name" ]. "" ;?>
Loading multiple files can be implemented using, for example, different name values for the input tag.
It is also possible to automatically obtain information organized into an array 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:
If such a form was submitted, the $_FILES["userfile"] , $_FILES["userfile"]["name"] , and $_FILES["userfile"]["size"] arrays will be initialized (in the same way , like $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 corresponding values for the received files.
Let's assume that the files /home/test/some.html and /home/test/file.bin were loaded. In this case, the $_FILES["userfile"]["name"] variable will have the value some.html , and the $_FILES["userfile"]["name"] variable will have the value file.bin . Likewise, the variable $_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 file uploads to the server is not that difficult. It is more difficult to ensure the required 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 required level of security when working with Uploads, see.
<<< Назад | Content | Forward >>> |
If you have any other questions or something is not clear - welcome to our | |
|
From the author: Hello friends. In this short article you will learn how to create a file upload form on your website. This will allow you to attach pictures and other files to the form and send the files to the server, where they will be processed. Let's begin.
You can download the source files of the current article from .
Let's start by creating a form that will have a field for uploading a file. What should you pay attention to here? Firstly, the field for sending a file must have a special type - type="file". Secondly, the file can only be sent in the body of the request, so the GET method for sending the form will not work; you only need to use the POST method - method="post". And thirdly, the form requires a special enctype attribute with a specific value - enctype="multipart/form-data". Without this attribute, the file simply will not be sent.
Based on the above, our code will be something like this:
< form class = "form-horizontal" method = "post" enctype = "multipart/form-data" action = "file.php" > < div class = "form-group" > < label for = "name" class = "col-sm-2 control-label" >File name< / label > < div class = "col-sm-8" > < input type = "text" id = "name" class = "form-control" name = "name" placeholder = "File name" > < / div > < / div > < div class = "form-group" > < label for = "file" class = "col-sm-2 control-label" >File< / label > < div class = "col-sm-8" > < input type = "file" name = "file" id = "file" > < / div > < / div > < div class = "form-group" > < div class = "col-sm-offset-2 col-sm-8" > < button type = "submit" id = "submit" class = "btn btn-primary" >Send< / button > < div > < / div > < / div > < / div > < / form > |
As a result, we will get something like this:
The field for uploading files does not look very attractive, but, nevertheless, it will cope with its task without problems: the file can be attached and sent to the server. In the next article we will try to beautifully design the field for uploading a file, but for now let's check if the file is being uploaded. As you can see, the form will be sent to file.php, which is specified in the action attribute. Let's create this file.
In our article we will look at an example of creating a PHP script for uploading files to the server. Our simple file upload example will have 2 files: a form (form.html), a php file upload script (uploader.php).
Now let's look at everything in detail. First, let's analyze the form file form.html:
As you can see, this is a simple html code, there is nothing complicated here, the only thing is that if the form will upload files to the server, then the attribute must be specified enctype="multipart/form-data".
Our form will look like this:
ExamplePHP file upload script
Now let's look at the php file that will upload files to the server. Below is its source code:
// Where the file is going to be placed $target_path = 'uploaded_files/"; /* Add the original filename to our target path. Result is "uploaded_files/filename.extension" */ $target_path = $target_path . basename($_FILES ["file"]["name"]); if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_path)) ( echo "The file ". basename($_FILES["file"][ "name"]). " has been uploaded"; ) else( echo "There was an error uploading the file, please try again!"; )
How does the PHP file upload script work?
uploader.php is a simple PHP script for uploading files to the server, which will upload our files to a specific directory on the site, which is indicated by the line $target_path = "uploaded_files/";
Well, of course, we do a basic output of messages using if/else, so that it is clear whether our file is loaded or not.
Protection against hackers when downloading a file
We will consider not only protection in terms of hacking, but also other unwanted problems that arise when uploading files to the server.
PHP file wrapper
This is the first problem associated with uploading files to the server. When the downloaded file has a php wrapper, it does not mean that its extension will be php. It can look like image.jpg (.gif, .png…). But inside it looks like this:
Some craftsmen can also execute commands on the server by surfing the url:
$ curl http://server/uploads/shell.php?command=any_unix_command
Protection method:
For protection, you can implement MIME file checking. See an example below:
If($_FILES["file"]["type"] != "image/gif") ( echo "Sorry, we only allow uploading GIF images"; exit; )
This piece of php code checks whether the uploaded file is a GIF file. Paste this code before the php file upload script. Naturally, you can change the check to jpg, png or other files you need.
In truth, this method of protection can be bypassed if you send the header header with MIME instructions. To do this, it is necessary to check the availabilitytags in the downloaded file.
Upload file size limit
You may also have problems with large file sizes taking up your disk space. To do this, you need to write a limit on the size of the uploaded file.
You can do this using a form; to do this, you need to add the following line to the html context of the form:
This hidden input field will limit the size of the uploaded file. Or you can check the file size using PHP.
Write aboutphp script for uploading files can take a long time, but we have already discussed the basic principle of uploading files to the server. So if anyone has any more questions, ask them in the comments.
How to upload a file to the server using PHP? In this article we will look at this issue in detail with examples.
HTML form for submitting a file
The first thing you need to know to upload files to the server is the features of the HTML forms that submit the file.
Here is an example of HTML code for this form: