In the operation of a web resource, it is convenient to use temporary files to store data during processing. After completion of work, the need to store such files disappears. The site may provide the visitor with the ability to download files. Data can be downloaded incorrectly or after downloading sent and deleted from the hosting. In these and many other cases, PHP offers the unlink () function to remove information from the file system provided by the hoster as a web resource.
Hosting conditions and file names
Creating a file on the hosting can execute PHP code due to the need for permanent or temporary data storage. Files can be downloaded through the pages of the site. In any case, the file name and path to it matters.
As a rule, data is placed in specially designated folders and cannot be placed at the location of the site code. Before deleting a file, it must be checked what exactly will be deleted.
Hostings, as usual, are Apache or Windows servers. For safe and stable operation of the web resource, it is advisable not only to control, but also to form the name of each file. Trusting a visitor to upload files with arbitrary names is not allowed.
To save the original name, you can create a special table of names matching. Each uploaded file gets a new name, but the exact original name is preserved. When creating a file, the site “chooses” the file name. Under these conditions, using the PHP unlink () function is safe and reliable.
File deletion
The file system provided to the web resource starts at $ _SERVER ['DOCUMENT_ROOT']. Each folder, starting with the root of the site, has its own access rights. It’s not customary to set locks and protections that harm the site.
If any operation is prohibited, it simply will not be executed. The site has worked and will continue to work.
It is not necessary to check the actual existence of a file before executing the PHP unlink () function. If something is wrong, an error of level E_WARNING is generated. By escaping the function call with the @ symbol, you can ignore this error. If you want to write professional code, you should check the path, file name and its actual presence before deleting.
Situations when the PHP unlink function does not work are hard to come up with. The only thing, it is important to take into account the extremely close attitude of any hosting to the case of letters and Cyrillic.
In order to avoid problems, both file names and the process of file deletion should be kept under control.