Computer lessons

Uploading files using PHP. Uploading files using PHP to Php server upload file

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


// 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 "

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

" ;
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:


Send these files:






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:

File upload form



What's unique about this form:

  1. The form tag must contain the enctype="multipart/form-data attribute. This attribute indicates that the form will submit a file. By default, the enctype attribute is set to application/x-www-form-urlencoded .
  2. The form must contain a hidden attribute (type="hidden") with the name MAX_FILE_SIZE whose value (value) indicates the file size. In theory, browsers should report when a file is oversized, but in practice browsers do not support this. I think this attribute can be omitted.
  3. To select the file to be transferred, use the input tag, which has the type="file" attribute.

After the server receives an HTTP request from such a form, it writes the file to a temporary folder on the server.

If you want the file to be saved to a different directory at this stage, specify it in the upload_tmp_dir directive of the php.ini file.

To move an uploaded file to a new location, use the move_uploaded_file function.

But before we start working with this function, we must examine the two-dimensional $_FILES array, through which we access the characteristics of the uploaded file.

So, after the script received the form data with the transferred file, it wrote the file into a special folder, and wrote the data about the file into a two-dimensional array $_FILES .

Let's look at an example that displays the contents of the $_FILES array on the screen.

File upload form


"; ) else ( echo "
", print_r($_FILES), "
"; } ?>

This is what we get as a result of this script:

Fig.1. $_FILES array.

Now let's look at what is contained in this array.

Our two-dimensional $_FILES array has one element, filename . This is the value of the name field from the form element:

Data for this file:

  • $_FILES["filename"]["name"] - file name;
  • $_FILES["filename"]["type"] - file type;
  • $_FILES["filename"]["tmp_name"] - full path to the temporary directory on the disk;
  • $_FILES["filename"]["error"] - contains the error code, which is 0 if the operation was successful;
  • $_FILES["filename"]["size"] - file size.

It would be possible to specify two fields for files in the form, for example like this:


In this case, our array would look like this:


Fig.2. $_FILES array.

So, now we know how the $_FILES array is structured and the next step is to put the resulting file in the location we need.

function move_uploaded_file

As I already wrote, the move_uploaded_file function is used to move an uploaded file to a new location.

The syntax of the move_uploaded_file function is:

move_uploaded_file (from where to transfer, where to transfer)

The move_uploaded_file function returns a boolean value:

  • TRUE - if successful,
  • FALSE - if the first argument is a loaded file, but for some reason cannot be moved to the specified location, in this case no action is taken.

Let's use this function in an example:

File upload form


"; ) else ( move_uploaded_file ($_FILES["filename"]["tmp_name"], __DIR__ . DIRECTORY_SEPARATOR . $_FILES["filename"]["name"]); ) ?>

This script moves the image to the same folder in which it itself is located. To do this, we use PHP's built-in constants to specify the path:

  • __DIR__ is one of the “magic” constants; it contains the file directory.
  • DIRECTORY_SEPARATOR is a predefined constant containing the path separator. For Windows OS it is “\”, for Linux OS and others it is “/”.

Note: If the resulting file already exists, it will be overwritten.

is_uploaded_file function

There is one more function that must be used when working with uploading files to the server. This is the is_uploaded_file function and is used for security reasons.

is_uploaded_file - Determines whether the file was uploaded using HTTP POST and returns TRUE if so.

Using this function is useful to ensure that a malicious user does not try to trick the script into working with files it shouldn't - for example /etc/passwd.

Please note: for the is_uploaded_file function to work correctly, you need to pass the path to the file on temporary storage on the server, that is, an argument like $_FILES["filename"]["tmp_name"] , but the name of the uploaded file on the client machine ($_FILES[" filename"]["name"]) does not apply here.

Our final example script that handles the file submission form would look like this:

File upload form


"; ) else ( // Check if the file is uploaded if(is_uploaded_file($_FILES["filename"]["tmp_name"])) ( // If the file is uploaded successfully, move it // from the temporary directory to the final one move_uploaded_file ($_FILES ["filename"]["tmp_name"], __DIR__ . DIRECTORY_SEPARATOR . $_FILES["filename"]["name"]); ) else ( echo("Error loading file"); ) ) ?>

Limiting file size

In some cases, you need to limit the size of the file that can be uploaded to the server. For example, to allow only files no larger than 3 MB to be uploaded to the server, the above script contains the code:

1024*3*1024) ( echo("File size exceeds three megabytes"); exit; ) ... ?>

The maximum upload file size can also be set using the upload_max_filesize directive in the php.ini file. The default value of this directive is 2 MB:

$upload_max_filesize) ... ?>

PHP.ini settings for uploading files to the server

So, we learned about the upload_max_filesize directive of the php.ini file, which sets the maximum size of the uploaded file. What other directives in the php.ini file are responsible for uploading files to the server?

By the way, if you want to find out where your php.ini file is located, run the script:

So, the list of directives in the php.ini file:

  • file_uploads - the ability to prohibit or allow uploading files to the server as a whole, enabled by default (value On).
  • post_max_size - general upper limit on the size of data transmitted in a POST request. If you need to transfer multiple files at the same time, or work with large files, change the value of this directive. The default value is 8MB.
  • upload_max_filesize is the directive we have already discussed. Don't forget to also change post_max_size if necessary.
  • upload_tmp_dir - temporary directory on the server where all uploaded files will be placed.

That's all I wanted to tell you on the topic "Uploading files to a server in PHP".

12/27/16 19K

Today I want to tell you about various situations related to uploading files to the server using PHP scripts. I will try to give examples of both the simplest file upload and multi-upload using move uploaded file PHP.

To upload files to the server. First of all, you need to create an HTML form with a file input field. Then attach a PHP script to it, which will move the file to the specified directory. To upload a file to the server using a PHP script, follow these steps:

  1. Create a simple HTML form: You will need a simple form with the option to specify a file. It is located in the basic.php file:

Basic File Upload

Basic File Upload


The above code is required to create the form. Once the user selects a file and clicks the Upload button, the form will submit data using the POST method on the same page, since the basic.php file is specified as the handler:

Important: don't forget to add enctype=”multipart/form-data” into the tag

.

  1. We create a PHP script to process the download form. In PHP, all information about uploaded files is contained in the global variable $_FILES. That is, using $_FILES you can check whether a file has been downloaded. If the file has been uploaded, you can move it to the desired directory using the move_uploaded_file PHP function:

The above code checks if the user has downloaded the file. If the file is downloaded, then we move the file to the specified directory. In the above script, we are moving the file to the same folder where the basic.php file is located.

Below is the complete PHP version of move uploaded file example:

Basic File Upload

Basic File Upload


Please do not test this PHP move uploaded file example on the server. It is not security compliant and was created specifically to demonstrate how to upload files using PHP.

Question: Why is the above script insecure?
Answer: Using the script above, you can upload any type of file to the server. That is, if you use the script in this form on a “live” server, then any hacker will be able to upload their own PHP scripts and hack your site and server.

A little later we will talk in more detail about protecting the script for uploading files to the server.

What is $_FILES?

$_FILES is a global variable in PHP like $_POST or $_GET . It is an associative array that contains information about the uploaded file using the HTTP POST method.

That is, if we run print_r($_FILES) for the above script, we will get the following information:

Array ( => Array ( => upload-file-php.jpg => image/jpeg => /Applications/XAMPP/xamppfiles/temp/phpcQiYhh => 0 => 6887))

That is, for each field an element is created in the array. If you create , then the element name will also be changed to test . For example:

Array ( => Array ( => upload-file-php.jpg => image/jpeg => /Applications/XAMPP/xamppfiles/temp/phpcQiYhh => 0 => 6887))

Now, for each input file moved using move uploaded file PHP, five elements are created ( name, type, tmp_name, error, size). Let's take a closer look at these elements:

  1. name: contains the name of the file uploaded by the user. If you load the abc.txt file into the browser, the name element will be called abc.txt ;
  2. type: the type of the uploaded file, or mime-type to be more precise. For a JPG file, this element will have the value image/jpeg . If you load text, the element will receive the value text/plain . The mime-type will be different for different file types. Below are the most common mime types:
  • JPEG: image/jpeg ;
  • PNG: image/png ;
  • Text: text/plain ;
  • Word: application/msword.
  1. tmp_name: Temporary location for the downloaded file. This path can be changed in the upload_tmp_dir variable specified in the php.ini file.
  1. error: error information. Includes the type of error encountered during the download process. For example, when the file size exceeds the maximum or when no file was specified to download. For any error that occurs there is a numeric value and a constant. Below is a complete list of errors that may occur in PHP move uploaded file example:
  • UPLOAD_ERR_OK (value 0). Indicates that the file was successfully downloaded without errors;
  • UPLOAD_ERR_INI_SIZE (value 1). The file size exceeds that specified in the upload_max_filesize variable in the php.ini file;
  • UPLOAD_ERR_FORM_SIZE (value 2). The file size exceeds the value set in the MAX_FILE_SIZE form variable;
  • UPLOAD_ERR_PARTIAL (value 3). The file has not been fully downloaded;
  • UPLOAD_ERR_NO_FILE (value 4). There is no file to download;
  • UPLOAD_ERR_NO_TMP_DIR (value 6). The specified directory for temporary storage does not exist;
  • UPLOAD_ERR_CANT_WRITE (value 7). The file cannot be written to disk.
  1. size: size of the uploaded file in bytes.

What is move_uploaded_file?

move_uploaded_file is a function that moves an uploaded file from a temporary directory to a destination folder. Before moving move_uploaded_file, PHP checks whether the file specified in the post HTTP method has been uploaded.

If the file was successfully moved, you will receive a true or false response. In the first example we used the following line of code:

move_uploaded_file($_FILES["inputfile"]["tmp_name"], $destiation_dir)

Now let's do it nicely and display the information:

if(move_uploaded_file($_FILES["inputfile"]["tmp_name"], $destiation_dir))( echo "File Uploaded" ) else( echo "File Not uploaded" )

Changing the upload file size limit

Each file upload form must have a size limit, otherwise users will end up uploading bulky files. There are two ways to set a limit on move uploaded file PHP:

  • The PHP.ini file has a special variable upload_max_filesize, which is responsible for the maximum size of uploaded files. The following is a line from php.ini that limits the size of uploaded files to 20 MB: upload_max_filesize = 20M.
  • If the uploaded file is larger, the user will receive an UPLOAD_ERR_INI_SIZE error or the value “2” in the $_FILES variable. It is important to note that the value of the upload_max_filesize variable should not exceed the value of the post_max_size variable specified in php.ini;
  • You can limit the size of the uploaded file by placing a hidden input element called UPLOAD_ERR_INI_SIZE in the upload form. You can do it like this: .

If you need to greatly increase filesize, then do not forget to change the execution time of PHP scripts.

How to secure PHP file upload script

Now you know how to limit the size of uploaded files and know how to identify the types of files that users upload. It's time to take care of the security of our PHP move uploaded file example.

As an example, we will prevent users from uploading jpeg files larger than 1 MB. Set the appropriate limit in the upload_max_filesize variable in the php.ini file. Below is an improved version of the script:

Secure File Upload

Secure File Upload


Multi-upload of files using a PHP script

You can upload multiple files at once using $_FILES and move_uploaded_file PHP. Below I will tell you about two ways to multi-upload files using a PHP script:

  1. Using different Input names.
  2. Using the same input name, but using an array.

1. Using different Input names:

You can upload multiple files at once using multiple input elements. As mentioned earlier, if we create multiple input elements, then several main elements will be created in $_FILES. For example, for the form below:

$_FILES will present an array with the following content:

Array ( => Array ( => 20141002_094257.jpg => image/jpeg => /Applications/XAMPP/xamppfiles/temp/phpoBWrBZ => 0 => 2669096) => Array ( => 20141002_094247.jpg => image/jpeg = > /Applications/XAMPP/xamppfiles/temp/phpjwUmVZ => 0 => 2207657))

The PHP move uploaded file example below should be written taking into account the fact that one element is for an avatar (image), and the other is for uploading a resume ( file in .doc format):

Multiple File Upload

Multiple File Upload



2. We use one input field, but using an array:

As with other input types, for move uploaded file PHP we can use an array with the input type specified in php. That is:

That is, for the HTML above, $_FILES will provide data with the following structure:

Array ( => Array ( => Array ( => upload-file-php.jpg => variable-scope-php.jpg => magic-constants.jpg) => Array ( => image/jpeg => image/jpeg => image/jpeg) => Array ( => /Applications/XAMPP/xamppfiles/temp/phpML5kOy => /Applications/XAMPP/xamppfiles/temp/phpNZbuw7 => /Applications/XAMPP/xamppfiles/temp/phpO8VFAk) => Array ( => 0 => 0 => 0) => Array ( => 6887 => 8036 => 9967)))

Download the code used in the article

This publication is a translation of the article “File Upload With PHP Script”, prepared by the friendly project team

Good bad