Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would say that in order to do this safely, you should <a href="http://php.net/manual/en/function.flock.php" rel="nofollow">acquire an exclusive lock</a> on the file at the beginning of the script, read it all into memory once, modify it in memory, then write it back to the file at the end. This would also be considerably more efficient in terms of disk I/O.</p> <p>You should also alter the cron job to run less frequently. It is likely that the reason you currently have this problem is because two processes are running at the same time - by locking the file, if this is the case, you risk having the processes stack up waiting to acquire a lock. Setting it for every 5 minutes should be good enough - your IP shouldn't change <em>that</em> often!</p> <p>So do this (<strong>FIXED</strong>):</p> <pre><code>#!/usr/bin/php &lt;?php // Settings $hosts = array( 'me.gotdns.com', 'me2.gotdns.com' ); $filename = '/etc/hosts.allow'; // No time limit (shouldn't be necessary with CLI, but just in case) set_time_limit(0); // Open the file in read/write mode and lock it // flock() should block until it gets a lock if ((!$handle = fopen($filename, 'r+')) || !flock($handle, LOCK_EX)) exit(1); // Read the file if (($contents = fread($handle, filesize($filename)) === FALSE) exit(1); // Will be set to true if we actually make any changes to the file $changed = FALSE; // Loop hosts list foreach ($hosts as $host) { // Get current IP address of host if (($ip = gethostbyname($host)) == $host) continue; // Find the entry in the file $replaceWith = "#SO{$host}\nsshd : {$ip}\n#EO{$host}"; if (preg_match("/#SO{$host}(.*?)#EO{$host}/si", $contents, $regs)) { // Only do this if there was a match - otherise risk overwriting previous // entries because you didn't reset the value of $result if ($regs[0] != $replaceWith) { $changed = TRUE; $contents = str_replace($regs[0], $replaceWith, $contents); } } } // We'll only change the contents of the file if the data changed if ($changed) { ftruncate($handle, 0); // Zero the length of the file rewind($handle); // start writing from the beginning fwrite($handle, $contents); // write the new data } flock($handle, LOCK_UN); // Unlock fclose($handle); // close </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload