ComputersFile Types

PHP: uploading a file to the server

Downloading files via PHP is a very interesting matter, which you should 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 meet security rules.

Such things should be brought to the end, even if it takes a long time. If you leave a hole 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. Where more time and lines of code are spent on security.

The danger is that if you do not do any checks, any attacker will be able to download their scripts to your server. In this case, he will have full access. He can do anything he wants:

  • Delete the database;
  • Delete site files;
  • Change site files;
  • Add your ads to your site;
  • Download viruses;
  • Redirect all users to their sites;
  • And much more that the burglar will come to mind.

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

How to implement the test will be shown later, when you directly examine the file download script.

Creating a PHP Form

The file download form looks very simple. Enough of the review buttons and download buttons.

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

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

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

How should this work?

When you click on the browse button, you should open a window, where you will be asked to select a file.

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

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

After clicking on the download button with the handler file, you can give out any information.

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

Typically, this detailed information is used to debug the code. In this way, you can check that the data is being transferred and the record is going to the directory you need. That is, even the file name does not indicate. Because this is extra information that the user does not need.

It makes sense to output data about the name only if the user loads several files. We will consider this case a little further. We will not run ahead.

Customize

In PHP, uploading a file to a server requires certain settings to be made 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 of your sites on the server, not just one of them. Therefore, set the maximum size based on what you will be uploading users. It is not recommended to set too large values.

After you change the values in these settings, the server needs to be rebooted. Otherwise, the settings will not take effect, since they are read at the time of server loading.

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.

Array with file

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

In order to see what kind of information is contained in this array, it is enough to write the following in the handler file:

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

As you can see, there are many fields in this array. All of them are important for us. The first field stores the file name 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 finishes, it will be deleted.

The error field stores the error code. About this a little further. Size - size in bytes.

Errors

The download of a file through PHP is always accompanied by an error code. The error message is enclosed in the "error" field. In the screenshot, the error is zero.

Consider the values of all errors:

Above it was said about the parameter, which can be specified in the usual HTML.

Here is an example of a form for uploading a file, where a limit is specified in the size of the file being uploaded.

PHP: file download script

How is everything done in practice? In PHP, the file is loaded with the copy command. If you were interested in the question of how to upload a file, the answer is simply copy, which uses two parameters - the source file and the destination file.

But, as it was written above, this can not be limited for security reasons. For example, to check what kind of file we are loading, we can use the field type in the array $ _FILES. First, we'll figure it out with a test, and then move on to the full script

Let's say you want users to upload a photo with the resolution of only GIF, JPEG or PNG. You can specify it like this.

If ($ _ FILES ['file_upload'] ['type']! = "Image / gif") {
Echo "Sorry, we support downloading only Gif files";
Exit;
}

If you want to ship all 3 types, simply add an additional condition with another type of image.

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

In our case, when the work proceeds with the download from the computer to the server, you can do so

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 must always be set differently, and the extension should be specified depending on the file.

You can define the extension in many ways. It all depends on the erudition of the developer. One of the fastest ways (the difference in tenths of seconds) of defining an extension is the following code.

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

$ Ext = $ path_info ['extension'];

In the variable $ ext we will store the required extension. And the file name can be set randomly using md5. If you plan to download many files, it's better to load them into different folders. So it will be more convenient. Especially if you want to clean it.

The code to download will be as follows.

/// availability of photos

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

{

Echo ("

No file specified.

Back ... ");

Exit;

}

///. Let's say you have the permission to upload large files (video) for a project on the server, but there will be only photos, and users need to limit

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

{

?>

The maximum allowed image size is 2 MB

Back ...

Exit;

}

// create folders

// create current month folder

If (! File_exists ("img /". Date ("M")))

{

Mkdir ("img /". Date ("M"));

}

// create a folder of 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 successfully downloaded");

}

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

}

Multiple files

Downloading multiple files (PHP) occurs using additional fields in the form.

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

The ideal option is the ability to select a large number of files at once by pressing a single button.

For this, we create the form with this code.

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

To check, you can again use var_dump ($ _ FILES);

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

  1. $ _FILES ["file1"] ["name"] [0]
  2. $ _FILES ["file1"] ["name"] [1]
  3. And so on.

In parentheses, the file number in the array is written. Counting from scratch. We process them in the same way, just set the loop and, when accessing the above code, we add the index [$ i] at the end.

$ I = 0;

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

{

/// insert the above code

}

Thus, you will have to download files through PHP in a single cycle, without unnecessary repetition of the code, as is usually the case if you use a version with a static number of files (the last photo).

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.birmiss.com. Theme powered by WordPress.