What are the risks of writing files to the Apache server with PHP and how to avoid them?

6

I am writing an HTML file with part of a page, to be used later by HTMLDocX in generating a .docx file % (see this question related).

To write ob_start and ob_get_clean use to put the content in a variable:

ob_start();

// parte da página aqui

$var = ob_get_clean();

And then with file_put_contents saved to a file in a server directory:

file_put_contents('/pasta/arquivo'.$id.'.html', $var); // cria o arquivo com o id criado antes.

So, in the HTMLDocX template just get the file with file_get_contents :

$html = file_get_contents('../../pasta/arquivo'.$id.'.html');

But every time I test this on localhost (I have not yet gone to the server), I have to change the directory permission on the nail (with chmod and such). I know that there must be a way to make this permission permanent, I have not yet seen it ... but then I was thinking that there could be serious security risks, since I am giving write permission to a directory (777).

In short, the question is:

  

What are the risks involved in the recording process and   subsequent access of a .hmtl file on an Apache server with PHP, and   how to avoid them? Is there a best practice for this?

In case it would be better to just save the HTML in the database and then access it through the mySQL query (I do this to generate the pdf, but pro docx I found it simpler to just save the file and then access HTMLDocX ...) p>     

asked by anonymous 23.10.2015 / 06:00

1 answer

2

Saving files to the server is safe as long as it is set up correctly. Using the 777 permission is a bad practice, but sometimes it is the only alternative when there is no root permission.

Ideally, you should assign write permissions only to the server (usually user www-data ) with chown and chmod .

In practice, as it is necessary to manipulate the files (mainly in the development environment), I use permissions 664 for files and 775 for directories, my user being the owner and the apache owner group, as follows:

drwxrwxr-x 24 meu-usuario www-data  4096 Out 23 13:20 arquivos
-rw-rw-r--  1 meu-usuario www-data  3710 Out 23 13:20 index.php

To configure the environment the commands are (such as root ):

chown -R www-data /var/www/html/
chmod -R g+w /var/www/html/

The first one changes the owner group to the server recursively and the second adds the write permissions to the group. By default the group already has execute (directories only) and read permission. The /var/www/html/ directory is the default for apache and your environment may be in another location.

However files created by apache / PHP will not be accessible by your user automatically, but you can configure a scheduled task with the crontab -e (like root ) command and adding the line below in the editor to run the update every 5 minutes.

*/5 * * * * chown -R seu-usuario:www-data /var/www/html/ && chmod -R g+w /var/www/html/
    
23.10.2015 / 17:24