PHP: uploading a file to the server

Uploading files via PHP is a very interesting thing that you need to approach very carefully. On the Internet you can find many examples of the implementation of file downloads, but not all of them are good and comply with security rules.

Such things need to be brought to an end, even if it takes a lot of time. If you leave a gap in the code, then your entire server may be at risk.

Security

Using PHP, uploading files to the server is quite easy. The code is very short and simple. Just a couple of lines. But such a method is dangerous. Much more time and lines of code are spent on security.

The danger is that if you do not check, any attacker can upload their scripts to your server. In this case, he will have full access. He can do whatever he wants:

  • delete bases;
  • delete site files;
  • Modify site files
  • add your ads to your site;
  • Download viruses
  • redirect all users to their sites;
  • and much more that comes to the mind of the cracker.

You always need to check what kind of file the user is trying to download. If, for example, you upload only photos, you need to verify that this file is exactly an image. Otherwise, anything will be downloaded to you.

How exactly to implement the verification will be shown later, by directly reviewing the file upload script.

PHP form creation

The file upload form looks very simple. There are enough browse buttons and download buttons.

php file upload form

We will not describe the creation of the form, as it is easy. Further instructions assume that you already have basic HTML concepts (otherwise you would not be looking for information about loading in PHP).

But note that to transfer data in the form, you need to add the enctype attribute.

upload files via php

Otherwise, data about the file will not be transmitted to the handler.

How should this work?

easy php file upload
When you click on the browse button, a window should open where you will be prompted to select a file.

After that, the path where the file is located should appear.

fast file upload via php

If the path does not appear, then do this again.

After clicking on the download button with a file handler, you can display any information.

form for uploading files via PHP

For example, you can write a line that says that a file with such-and-such name was successfully uploaded to such-and-such folder. Of course, the file name will always be different.

Typically, such detailed information is used to debug code. Thus, you can verify that the data is being transferred and writing to the directory you need. That is, even the file name is not indicated. Since this is superfluous information that the user does not need.

It makes sense to output data about the name only if the user uploads several files. We consider this case a little further. Let's not get ahead of ourselves.

Customization

In PHP, uploading a file to the server requires certain settings that need to be done in the php.ini file. There are a lot of settings in this file. We all do not need them. We are interested in three lines: file_uploads, upload_tmp_dir and upload_max_filesize.

Please note that these settings will affect all your sites on the server, and not just any one. Therefore, set the maximum size based on what users will download from you. Setting values ​​too high is not recommended.

After you have changed the values ​​in these parameters, the server needs to be rebooted. Otherwise, the settings will not take effect, as they are read at the time the server boots.

You can do this in the console by connecting via SSH to the server. It is enough to enter the command service httpd restart, and after that the settings will take effect.

Another way is to restart through the ISP panel or through the provider's billing panel.

how to reboot the server

Array with file

In PHP, a file is loaded using the $ _FILES array. It contains all the information about the files that we will upload.

In order to see exactly what information is contained in this array, it is enough to write the following in the handler file.

php file download

Select any file and click "Download." The handler page displays information stored in $ _FILES. The variable is written completely in capital letters. PHP is a case-sensitive language.

php upload files to server

As you can see, there are many fields in this array. All of them are important to us. The first field stores the name of the file in the form in which it is used on your computer.

The type column indicates the file type. The tmp_name field corresponds to the name of the temporary file. After the script is finished, it will be deleted.

The error field stores the error code. More about this later. Size - size in bytes.

Mistakes

PHP file uploads are always accompanied by an error code. The error message is enclosed in the "error" field. In the screenshot, the error is zero.

php file upload script

Consider the values ​​of all errors:

loading errors
It was said above about a parameter that can be specified in regular HTML.

Here is an example of a form for uploading a file, which indicates a limit on the size of the uploaded file.

html file upload form

PHP: file upload script

How is everything implemented in practice? In PHP, the file is uploaded with the copy command. If you were interested in the question of how to download a file, then the answer would be just copy, which uses two parameters - the source file and the destination file.

But, as mentioned above, this should not be limited to security purposes. For example, to check what kind of file we are loading, you can use the type field in the $ _FILES array. First, we’ll deal with the verification, and then move on to a full-fledged script

Suppose you want users to be able to upload a photo with a resolution of only GIF, JPEG or PNG. This can be indicated like this.

if ($ _ FILES ['file_upload'] ['type']! = "image / gif") {
echo "Sorry, we only support downloading Gif files";
exit
}

If you want to load all 3 types, just add an additional condition with a different type of image.

Copying is done like this: copy (file 1, file 2).

In our case, when it comes to downloading from a computer to a server, you can do this

copy ($ _ FILES ['file_upload'] ["tmp_name"], "1.jpg")

That is, the file will be copied with the name 1.jpg. This is not entirely correct. In this case, this is just an example. The file name should always be specified differently, and the extension should be specified depending on the file.

There are many ways to define an extension. It all depends on the erudition of the developer. One of the fastest ways (the difference in tenths of a second) of determining the extension is the following code.

$ path_info = pathinfo ($ _ FILES ['photo1'] ["name"]);

$ ext = $ path_info ['extension'];

In the variable $ ext, we will store the desired extension. And the file name can be set randomly using md5. If you plan to upload many files, it is better to load them in different folders. It will be more convenient. Especially if you want to clean.

The code to download will be as follows.

php file type check

/// availability of photos

if ($ _FILES ['photo1'] ['tmp_name'] == null)

{

echo ("<p> <strong> File not specified. </strong> </p> <p> <a href='javascript:history.back()'> Back ... </a> </p> ");

exit

}

///. Suppose you are allowed to upload large files (videos) for some project on the server, but only photos will be here, and users need to be limited

if (($ _FILES ["photo1"] ["size"]> 1024 * 1024 * 2)

{

?>

<p> Maximum allowed image size <strong> 2 MB </strong>

<p> <a href='javascript:history.back()'> Back ... </a> </p>

<?

exit

}

// create folders

// create current month folder

if (! file_exists ("img /". date ("M")))

{

mkdir ("img /". date ("M"));

}

// create the folder for the current day

if (! file_exists ("img /". date ("M"). "/". date ("d")))

{

mkdir ("img /". date ("M"). "/". date ("d"));

}

/// file extension

$ path_info = pathinfo ($ _ FILES ['photo1'] ["name"]);

$ ext = $ path_info ['extension'];

/// generate the file name

$ id = md5 (date ("YMd"));

if (copy ($ _ FILES ['photo1'] ["tmp_name"], "img /". date ("M"). "/". date ("d"). "/". $ id. $ ext) )

{

echo ("file uploaded successfully");

}

/// any further actions (writing to the database, etc.)

}

Multiple files

Uploading multiple files (PHP) is done using additional fields on the form.

upload multiple php files

This method is not very good, as it limits the number of files to download. Moreover, it is considered a bad form in programming. Try to do everything dynamic.

The ideal option is the ability to select a large number of files at once with the click of a button.

To do this, create the form with this code.

<form method = "POST" action = "Link to the handler file" name = "upload_form" enctype = "multipart / form-data">

<p>

<input class = "form_upload" type = "file" name = "file1 []" multiple value = "Overview">

<input class = "form_upload" type = "submit" name = "upldFile" value = "Add" />

</p>

</form>

Notice that the word multiple is added and the name is given as an array []. In this case, the $ _FILES array will be slightly different. You will get an array in an array.

For verification, you can again use var_dump ($ _ FILES);

All your files will be located in an array like this:

  1. $ _FILES ["file1"] ["name"] [0]
  2. $ _FILES ["file1"] ["name"] [1]
  3. Etc.

The number of the file in the array is written in brackets. Countdown from scratch. We process them in the same way, just set the cycle and add the index [$ i] at the end in the code described above.

$ i = 0;

while ($ _FILES ["file1"] ["name"] [$ i] <> '')

{

/// insert the above code

}

Thus, you will have through PHP uploading files to the server in one cycle without repeating the code, as is usually the case if you use the option with a static number of files (last photo).

Source: https://habr.com/ru/post/C46750/


All Articles