Loading files to the server using PHP. Example of downloading files to the server (UPLOAD) in PHP How to download PHP file

Surely you often download various files on sites. For example, uploaded avatars on the forum, Photos on social networks, various videos on video hosts, just files on file sharing. And here in this article you will learn how to upload files to the server in PHP. It is through Php. In most cases, this is implemented.

First of all, what to learn is that herself HTML formin which the file is substituted must be not quite normal, here is an example HTML code Such a form:





The key point here is an attribute " enctype."With the meaning" multiPart / Form-Data". Will not work without it.

"In which we still do not download the file, and we will pass a little at various important points that must be taken into account, otherwise security may affect:

Print_R ($ _ Files);
?>

As a result, you will see the contents. global two-dimensional array $ _files:

  • name. - The name of the downloaded file.
  • type - Mime-Type Downloadable file. This is perhaps the most important parameter for security. And always when receiving files must be checked Mime-Typeotherwise there are no problems. In the next article we will talk about it 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 carry it to another place. In fact, the file is already loaded, and we only need to move it to the desired folder on the server.
  • error - error code. If a 0 , There are no errors.
  • size - size of the downloaded file. This is also a frequently used option, and it should also be checked to limit the size of the downloaded files. Of course, this size itself is limited, however, for any pictures, this size is clearly overestimated (as a rule, he 10 MB).

And all these parameters are present for each downloadable file (each of which is an array in a two-dimensional array. $ _Files.).

Now let's finish with download files to the server in PHPAnd for this we will write such a code (""):

$ uploadfile \u003d "images /".$_ files [" somename "] [" Name "];
Move_uploaded_File ($ _ Files ["Somename"] ["TMP_NAME"], $ uploadfile);
?>

That is, at first we will specify the path to the downloadable file on the server. Here we want to put the file in the directory " images"With the same name that was before the file. And the function move_uploaded_File () We move the file to the directory of its selected directory from its temporary storage.

However, pay attention, it is very important! So use code in no case, otherwise your site will threaten a serious danger! In fact, at the moment it can be downloaded absolutely whatever: any executable files, scripts, HTML PAN And other very dangerous things. Therefore, it is necessary to check the downloadable files to the server very carefully. And so we will deal in the next article. Because the topic is very important, then I advise you to subscribe to updates, so as not to miss this article.

You have a JavaScript blocked in your browser. Allow JavaScript to work the site!

Loading files to the server

Short Exours in Upload

What is Upload Files, or why not working
copy ("C: \\ Images \\ sample.jpg", "http://mysite.ru/uploads/sample.jpg")

Even if you have only one computer at your disposal, on which the server and the workstation are aligned, do not forget that PHP uses the client / server technology. The file that we want to upload is usually located on the client's car, i.e. user, ordinary site visitor. Destination is the server. In order to make the file transfer process, we need the following form:

Send This File:

In this case, the URL of your PHP script must be specified in the Action field, which will continue to process the downloaded files. The hidden Max_File_size field must precede the file selection field, and contain the maximum allowable file size in bytes. Its assignment is to check the file size even until the file is sent to the server. It should save the user from a long and unsuccessful download of the file to the server and the formation of excess traffic, but should not be particularly relying on this restriction, as it is easy to get around it.

What happens when the user chose a file on his disk, and pressed the "Send File" button? The browser sends the file to the server where the PHP interpreter places it in his temporary directory by assigning it a random name and executes the script specified in the Action field.

How should Upload.php look like?

$ uploaddir \u003d "/ var / www / uploads /"; if (Move_uploaded_file ($ _ files ["userfile"] ["tmp_name"], $ uploaddir. $ _files ["UserFile"] ["name"])) (Print "File Is Valid, and Was SuccessFully uploaded.";) ELSE (PRINT "THERE SOME ERRORS!";)

When writing a script, a natural question arises: how to get information about the downloaded file and reach the file itself. If you use PHP version 4.1.0 and older, it will be best to refer to the global $ _files array. For each downloaded file, it contains a hash array, with the following data:

  • $ _Files ["userfile"] ["Name"] - the original file name, such as the user saw it, choosing the file;
  • $ _Files ["UserFile"] ["Type"] - Mime / Type file, for example, can be image / gif; This field is useful to save if you want to provide an interface for downloading downloaded files;
  • $ _Files ["UserFile"] ["Size"] - the size of the downloaded file;
  • $ _Files ["UserFile"] ["TMP_NAME"] - the full path to the temporary file on the disk;
  • $ _Files ["userfile"] ["error"] - Starting with version 4.2.0, contains an error code that is 0 if the operation has passed successfully.

For PHP version below 4.1.0, this array is called $ http_post_files. Do not forget that, unlike $ _Files, this array is not superglobal and when accessing it, for example, from a function, it is necessary to explicitly specify the Global $ http_post_files;

If additional variables of the $ userfile_name, $ userfile_type, $ userfile_size, $ userfile_type, $ userfile_size, will be created in the settings of your REGISTER_GLOBALS \u003d ON, ... Considering that, starting with version 4.2.0, the default settings register_globals \u003d off the use of these variables is not recommended, even if they Defined. The best way to get information about downloaded files is to use an $ _files array.

To work with downloaded files, it is best to use the built-in functions is_uploaded_file () and move_uploaded_file (), which check if the file was loaded, and placed it in the specified folder, respectively. You can find more detailed information on the manual pages. It is not necessary to invent a bike and work with temporary files yourself, copy them, delete. It has already been done to you and for you.

Server Tuning

I did everything right, but something does not work for me. Maybe I have incorrectly configured server?

If you "did everything right", but your code does not work, or it works incorrectly, do not rush to despair. Perhaps the problem is not in your hands, but in the wrong server settings. Here is a list of directives that are related to downloading files:

In the php.ini file:

  • If you want to know where your php.ini is located, perform
  • file_uploads. - Ability to ban or allow downloading files as a whole. Default on.
  • upload_max_FileSize - Maximum file size that can be downloaded. If you need to work with big files, change this setting. By default, 2m Do not forget to change POST_MAX_SIZE.
  • post_max_size. - A general limit on the top of the data transmitted in the POST request. If you need to work with big files, or send multiple files at the same time, change this setting. The default value is 8m.
  • upload_tmp_dir. - Temporary directory on the server to which all downloadable files will be placed. Check which rights are set on it (if you have difficulties at this stage, see the explanation at the end of the article). Such a directory must also have a user under which Apache is performed, there must also be the right to write to this directory. If you work with the Open_Basedir restriction enabled - then the temporary directory must be inside. You do not need to take care of her cleaning or the unique names, PHP solves this problem for you.

In file httpd.conf.:

  • First of all, make sure that you use the APACHE 1.3 web server (the latest version at the time of writing Article - 1.3.27). If you use Apache 2.0, you should read the following excerpt from the documentation:

    Do Not Use Apache 2.0 and PHP in A Production Environment Neither on UNIX NOR ON Windows.

  • If you received the message "POST METHOD NOT ALLODED", it means that you need to look for something similar to the following directives, and use the keyword of Allow: Order Allow, Deny Allow From All
  • Problems with downloading binary files - the classic question "Why files are fighting at UPLOAD". Here is the solution to the decision proposed by Dima Borodin (http://php.spb.ru): in the directory where the script lies, make the .htaccess file, in which we write: charsetdisable on to file httpd.conf. Add rows: CharsetRecodeMultipartForms Off

Small explanations, to this recipe: the above problem when the archives loaded to the server are not unpaid and the pictures are not displayed, it may occur due to the fact that the RUSSIAN Apache web server is used. The CharseTDisable Directive disables the Charset-Processing Module module, i.e. No transcoding when downloading files located in this folder will not occur. The CharsetRecodeMultipArtForms directive turns off the data transcoding transmitted by the POST method with the Content-Type: MultiPart / Form-Data header. Those. Binary data transmitted with such a setting will be left in original form, and all the rest of the site filling will be recoded according to the current server settings.

But at the same time complications may arise: be prepared for the fact that in some cases the text parts of the requests you will have to recodle yourself. This is what the documentation is said about this:

Use the CharsetRecodeMultipartForms directive, which appeared in PL23, but you still have to recode manually text part parts. To do this, you can use the Russian Apache API available in other modules or Russian Apache Perl API available from MOD_PERL.

One of the examples of the coding definition can be found here: http://tony2001.phpclub.net/detect_charset/detect.phps

The most recent documentation on Russian Apache is on its official website: http://apache.lexa.ru/.

Do not forget that after any configuration change, you need to restart your web server.

You can also configure APACH parameters using.htaccess:

PHP_VALUE Upload_max_Filesize 50m PHP_VALUE POST_MAX_SIZE 50M

Additional features

Loading multiple files at the same time

Example of the download form of several files:

Send These Files:


And do not forget to increase post_max_size.if many files are supposed

Automatic download files to the server

You should not forget that the files on the user's disk are confidential information to which neither JavaScript nor so much more PHP has a low relationship. Until the user selected the file with the help No matter what work with him can go and speech. And do not forget that this field input field is the VALUE attribute is protected from recording.

Storage of files in the MYSQL database

If you are gathered to store downloadable files in the database, you need to remember the following points:

  • You must use the BLOB field
  • Before laying to the database, do not forget to apply to the Mysql_escape_string () string
  • When displaying the file, you must specify the CONTENT / TYPE header

Remember that the script displays your HTML is in no way connected to the script that the image must output. These must be two different applications.

Storage of pictures in the database is not a good style. It is much more convenient to store in the database only to image files.

Obtaining image properties.

If you have a task to check the type or size of the picture before downloading the file to the server, you will need the GetImageSize () function. As an argument, it accepts the name of the file on the disk and returns the array, the first two elements of which is the width and height, respectively, the third is the type of image. If it is impossible to read the correct image from the specified file, the function returns a lie.

Loading files having a Russian-language name

When downloading to the server file, you need to check their original names for the presence of "non-standard" characters (for example, Russian letters). In the case of their presence, it is necessary to replace. The original file name can be found in the $ _files ["userfile"] ["NAME"] variable. How to recharge the Russian-language string to translite you can be found in the examples of PHP.

Download Status Display (Progress Bar)

It must be borne in mind that until the file is fully downloaded, PHP cannot operate or the size of the file or the percentage of its loading. Only when the file is already on the PHP server, it will be able to access the information. If you still need to implement such an opportunity, use the Java-applet.

Rights to files

Problems with Rights on the server (Upload_tmp_dir)

In unix-like operating systems, each folder, file, the link is set compliance with the permissions. They may look like RWX-RW-R- or as a number 754.

The availability of a file or directory depend on the user ID and the group identifier in which it enters. The mode as a whole is described in terms of three sequences, three letters each:

Owner Other group (U) (G) (O) RWX RWX RWX

Here, the owner, members of the group and all other users have the rights to read the file, write to it and its execution. Rights - any meaningful combination of the following letters:

r right to read. (four)
W right to record. (2)
x Right to execution (search in the directory). (one)

  • Install the owner of the user directory, with whose attractions is performed by Apache. This can be found from the httpd.conf file or viewing the list of processes on the server. The directory rights should be 700 (RWX ------).
  • Regardless of who the owner of the catalog, establish the rights of 777 (RWXRWXRWX).

    An example of implementing the download of pictures to the server.

    $ max_image_width \u003d 380; $ max_image_height \u003d 600; $ max_image_size \u003d 64 * 1024; $ valid_types \u003d array ("gif", "jpg", "png", "jpeg"); if (isset ($ _ files ["userfile"])) (if (is_uploaded_file ($ _ files ["userfile"] ["TMP_NAME"])) ($ filename \u003d $ _files ["userfile"] ["TMP_NAME"]; $ Ext \u003d Substr ($ _ files ["userfile"] ["Name"], 1 + STRRPOS ($ _ files ["userfile"] ["name"], ".")); If (FileSize ($ FileName)\u003e $ max_image_size ) (Echo "Error: File Size\u003e 64K.";) Elseif (! In_Array ($ Ext, $ valid_types)) (Echo "Error: Invalid File Type.";) ELSE ($ size \u003d getimagesize ($ FileName); if (($ Size) && ($ Size< $max_image_width) && ($size < $max_image_height)) { if (@move_uploaded_file($filename, "/www/htdocs/upload/")) { echo "File successful uploaded."; } else { echo "Error: moving fie failed."; } } else { echo "Error: invalid image properties."; } } } else { echo "Error: empty file."; } } else { echo "
    Send This File:
    "; }
  • In our article, we consider an example of creating a PHP file download script to the server. Our simple file download example will have 2 files: form (form.html), PHP file download script (Uploader.php).

    Now we will analyze everything in detail. First, analyze the form.html form file:


    As you can see this simple HTML code, there is nothing complicated here, the only one if the form will load files to the server, then the attribute must be registered enctype \u003d "multiPart /form-data ".

    Our form will look like this:

    ExamplePHP file download script

    Now we'll figure it out with the PHP file that will download files to the server. Below is its source code:

    // WHERE THE FILE IS GOING TO BE PLACED $ TARGET_PATH \u003d 'UPLOADED_FILES / "; / * Add the original filename to our target path. Result is" uploaded_files / filename.extension "* / $ target_path \u003d $ 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 php file download script?

    uploader.php is a simple PHP file download script to a server that will download our files into a specific site directory that is specified by the $ target_path \u003d "uploaded_files /" string;

    Well, by itself, we make elementary output of messages using if / else, it was clear, our file is loaded or not.

    Hacker Hacking Protection when downloading a file

    We will consider not only protection in terms of hacker hacking, but also other unwanted problems arising when downloading files to the server.

    PHP File Shell

    This is the first problem associated with downloading files to the server. When the download file has a PHP shell, and this does not mean that its extension will be PHP. It may have a view image.jpg (.gif, .png ...). But inside look like this:

    Some craftsmen can also execute commands on the server using the URL surfing:

    $ CURL http: //server/uploads/shell.php? Command \u003d Any_unix_Command

    Protection method:

    To protect, you can implement MIME file checking. Below see the example:

    If ($ _ files ["file"] ["type"]! \u003d "Image / gif") (echo "sorry, we only all uploading gif images"; exit;)

    This piece of PHP code checks whether the downloadable GIF file is the file. Insert this code before PHP file download script. Naturally, you can change the check on the JPG, the Pngi other files you need.

    It is truth to say, and this method of protection can be bypassed if you send a header header, with MIME instructions. To do this, it is necessary to check availability Tags in the downloadable file.

    Limiting the size of the downloaded file

    There may also be problems with large sizes of files that will occupy your disk space. To do this, write a limit on the size of the file being downloaded.

    You can do this using a form, for this you need to add the following line in the context of HTML form:

    This hidden input field will limit the size of the downloadable file. Or you can check the file size of the PHP tools.

    Write O.pHP file download script can be long, but we have already disassembled the basic principle of downloading files to the server. Therefore, if someone has more questions, ask them in the comments.

    Today, the file download service to the server (hosting) is found on all social networking sites, bulletin boards, dating sites, etc. The essence of it is to enable the visitor to the web resource to publish its files (photos, documents) on the Internet.

    When providing this service there is one substantial minus. The fact is that by allowing you to download the file to your server, we, as it were, install the door behind which constant control is necessary. Since in the visitor's file there may be not only useful information, but also a viral code that can later enable attackers to take possession of your server. Given this minus, you must carefully check the files before downloading to the server.

    But I will not intimidate you, but I'd rather imagine your attention already ready-made function (PHP script) to check and download files to the server. The function is 100% working. I myself use it on my sites. This feature is written for downloading image files (photos) in format.jpg, .gif, .png. But if you wish, you can make changes to adapt PHP script to your needs.

    Two checks are implemented in the php script:

    1. since the hoster limits the size of the file being downloaded (at the time of writing this material, I have an 8 MB limit on my hosting), then checking the maximum size is necessary;
    2. checking the file extension allows you to cut off unnecessary files before downloading.

    I hope the function code is sufficiently explained to deal with the download file to the server. But if you have any questions, I will be happy to answer in the comments.

    Now about how to implement it practically

    We place the PHP code function in a separate file: function.php and place it on the server in the root directory.

    And create an HTML file in which to post a photo download form: index.html

    upload.php - file form handler
    name \u003d "Button" - the name of the button, when you click on which the file download function is started to the server

    Loading multiple files

    Now we will analyze the case when you need to download multiple files to the server.
    To do this, we need in Function.php files update.php and index.html make some changes.





    Perhaps, this is all you need to implement the service for downloading a user file to the server (hosting).

    Another feature that is closely related to downloading graphic files (photos) is a function to change the size of the pictures:

    Multipart-forms

    • Web Ierfaces of postal services that allow you to add an application to the letter (attach), and for this you first need to download 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 the file download mechanism to the server;
    • Free software portals that are used to exchange files of various programs, etc.

    Downloading a file to a server is carried out using a multipart -form, in which there is a file loading field. The Encotype parameter indicates MultiPart / Form-Data:



    This will look like a given multipart form that will look like (you can try to see the result of the Multipart-forms, downloading some small file to the server):

    Multipart-forms usually use the POST transmission method. As can be seen from the previous example, this form has two fields:

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

    MultiPart form processing

    Before proceeding with writing a multipart-form processing script, you need to edit the configuration file php.ini. To allow downloading files to the server.

    The PHP PHP.ini configuration file has three parameters associated with downloading files to the server:

    • file_uploads \u003d ON - allows you to download files to the server via HTTP protocol;
    • upload_tmp_dir \u003d / TMP - Sets the directory to temporarily storing downloaded files;
    • upload_max_FileSize \u003d 2m - Sets the maximum amount of downloaded files.

    If your web server runs running the Linux operating system, then 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. Then it creates four variables of a superglobal array $ _files. This array contains information about the downloaded file.

    Variables defined for downloaded files depend on the PHP version and the current configuration. SuperGlobal $ _Files array is available from PHP 4.1.0. In case the configuration directive register_globals is set by the value oN.will additionally be declared variables with appropriate names. Starting from version 4.2.0, the default value for the Register_Globals option is off.

    The contents of the $ _FILES array for our example are given below. Please note that it is assumed to use the UploadFile name for the file selection field, in accordance with the above MultiPart form. Of course, the name of the field can be any.

    • $ _Files ["UploadFile"] ["Name"] - the file name before sending it to the server, for example, Pict.gif;
    • $ _Files ["UploadFile"] ["Size"] - the size of the received file in bytes;
    • $ _Files ["UploadFile"] ["type"] - MIME type of received file (if the browser was able to determine it), for example: image / gif, image / png, image / jpeg, text / html;
    • (So \u200b\u200bwe called the File download field) - contains the name of the file in the temporary directory, for example: / TMP / PHPV3B3QY;
    • $ _Files ["UploadFile"] ["error"] -An error code that may occur when the file is loaded. Key ["error"] It was added to PHP 4.2.0. With the appropriate error codes, you can familiarize yourself

    After completing the script, the temporary file will be deleted. This means that we must copy it to another place until the script is completed. That is, the algorithm for the work scenario of the file download to the server is:

    If the "Submit" button is pressed, the file will already be downloaded to the server and its name will be in the $ _files ["UploadFile"] ["Name"] variable. In this case, the script must immediately copy the file named $ _Files ["UploadFile"] ["TMP_NAME"] To some catalog (you need to write to this directory).

    File copying is performed by function copy () :

    Use only the copy () copy () function, and not moving, because:

    • The temporary file will be removed automatically;
    • If a temporary directory is on another media, an error message will be displayed.

    Suppose we need to download the file to the Uploads directory, which is located in the root directory of the web server (in the Documentroot directory).

    // Just in case, create a directory. If he is already created,
    // error message We will not see, because we will use the @ operator:

    @mkdir ("Uploads", 0777);

    // Copy the file from / TMP in Uploads
    // file name will be the same as before sending to the server:

    Copy ($ _ files ["UploadFile"] ["TMP_NAME"], "Uploads /". Basename ($ _ files ["UploadFile"] ["Name"]));

    In Linux, everything is much more complicated - we need to take into account the access rights to the Uploads catalog. Most likely, in this case, the function mkdir () It will not work, since we do not have the right to write to the Documentroot directory (usually / VAR / WWW / HTML or / HOME / HTTPD / HTML). Register as a root system, create a Uploads directory and change its owner and access rights as follows:

    // Create Uploads Catalog

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

    CHOWN APACHE: Apache Uploads

    // write resolution to everyone (777) + Installation of the fixing bit (1):

    CHMOD 1777 Uploads.

    The file size can be limited, if you wish, you can edit the .htaccess file and limit access to the Uploads directory - specify or specific users who can access the directory, or IP addresses.

    Now you can upload files to the server.

    We write PHP script download files to the server


    // Catalog in which we will receive the file:
    $ uploaddir \u003d "./files/";
    $ UploadFile \u003d $ uploaddir. Basename ($ _Files ["UploadFile"] ["Name"]);

    // Copy the file from the directory for temporary file storage:
    if (Copy ($ _Files ["UploadFile"] ["TMP_NAME"], $ uploadfile))
    {
    echo. "

    The file is successfully downloaded to the server.

    " ;
    }
    eLSE (Echo "

    Error! Failed to download the file to the server!

    "
    ; exit; )

    // Display information about the downloaded file:
    echo. "

    Information about the file loaded on the server:

    "
    ;
    echo. "

    The original name of the downloaded file: ". $ _Files ["UploadFile"] ["Name"]. "

    " ;
    echo. "

    MIME type of downloaded file: ". $ _Files ["UploadFile"] ["Type"]. "

    " ;
    echo. "

    The size of the loaded file in bytes: ". $ _Files ["size"] ["Size"]. "

    " ;
    echo. "

    Temporary file name: ". $ _Files ["UploadFile"] ["TMP_NAME"]. "

    " ;

    ?>

    Loading multiple files can be implemented using, for example, different Name values \u200b\u200bfor INPUT tag.

    It also provides for the ability to automatically obtain information organized into an array of several simultaneously downloadable files. To implement such an opportunity, use the same data syntax of the array from the HTML form as for multiple Select and CheckBox fields:


    Send These Files:






    In case such a form has been sent, arrays $ _files ["userfile"], $ _files ["userfile"] ["Name"], and $ _files ["UserFile"] ["Size"] will be initialized (in the same way like $ http_post_files for PHP 4.1.0 and earlier versions). If the register_globals configuration directive is set by the ON value, the associated global variables will also be initialized. Each of these variables will be a numerically indexed array of the corresponding values \u200b\u200bfor received files.

    Suppose that the /Home/test/some.html and /home/test/file.bin files were downloaded. In this case, the $ _files ["userfile"] ["name"] variable will have some.html value, and the $ _Files ["UserFile"] variable ["Name"] is file.bin. Similarly, the variable $ _Files ["UserFile"] ["Size"] will contain the size of the file some.html 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, it is not so difficult to organize downloading files to the server. It is more difficult to provide the necessary level of security, since loading files to the server can be used by attackers to the server. How to provide the necessary level of security, working with Uploads, see.



    <<< Назад Content Forward \u003e\u003e\u003e
    There are still questions or something incomprehensible - welcome to our