如何使文件编辑有条件?

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

</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?

You need to do it like below:-

<?php
 $file = '/etc/apache2/sites-available/000-default.conf';
 // Laravel Projects
 $newDirectory = "<Directory $path/public>
                 Allow Override all
                 Require all granted
              </Directory>";

  $virtualHostContent = file_get_contents($file);
  if( strpos($virtualHostContent,"<Directory $path/public>") === false) {
     $virtualHost = file_put_contents($file,str_replace("</VirtualHost>","$newDirectory

</VirtualHost>",$virtualHostContent));
  }
?>

This is what try catch blocks are Made for. I am on mobile so I can't provide you the code but here is a little idea for you:

Save the original file content and wrap your code in a try catch block. If an error occurs then reset your file to the original content in the catch block.

How can I add a condition on the way of file_put_contents to check first if if the same directory isn't exist,

Provided the file isnt huge, you can just read it into a string and check with strpos:

if(strpos(file_get_contents($file), "<Directory $path/public>") === false){
    $virtualHost = file_put_contents(...);
}