mercredi 6 septembre 2017

How can I make file editing conditional?

Here is my code:

$file = '/etc/apache2/sites-available/000-default.conf';
// Laravel Projects
$newDirectory = "<Directory $path/public>
                     Allow Override all
                     Require all granted
                  </Directory>";
$virtualHost = file_put_contents($file,str_replace("</VirtualHost>","$newDirectory\n\n</VirtualHost>",file_get_contents($file)));

It works as well. As you can see, it opens 000-default.conf file (in linux) and appends a new directory at the end of <VirtualHost> block.

My problem is, sometimes the rest of the code throws an error and when I run the whole script again, code above will append that directory twice.

How can I add a condition on the way of file_put_contents to check first if if the same directory isn't exist, then append it, otherwise don't do anything?

Aucun commentaire:

Enregistrer un commentaire