{"id":71,"date":"2006-10-20T03:04:40","date_gmt":"2006-10-20T01:04:40","guid":{"rendered":"http:\/\/www.nivas.hr\/blog\/2006\/10\/20\/filesystem-corruption-with-php\/"},"modified":"2006-10-20T03:04:40","modified_gmt":"2006-10-20T01:04:40","slug":"filesystem-corruption-with-php","status":"publish","type":"post","link":"https:\/\/www.nivas.hr\/blog\/2006\/10\/20\/filesystem-corruption-with-php\/","title":{"rendered":"Filesystem corruption with PHP"},"content":{"rendered":"<p>Writing to a file is easy with PHP. But what will happen if 2 processes try to write to a file at once? Exactly, your data might easily become corrupted and useless. You don&#8217;t want that to happen, of course. That&#8217;s why you need to implement file locking. flock() is your friend. For writing to a file, you want to obtain an exclusive lock on the file. There must never be concurrent writes to a file, after all. Here&#8217;s an example.<\/p>\n<p><!--more--> <?php\n$fp = fopen('foo.txt', 'w');\nif(flock($fp, LOCK_EX))\n{\nfputs($fp, \"some contents\");\nflock($fp, LOCK_UN);\n}\nfclose($fp);\n?><\/p>\n<p>For reading from a file, you want to obtain a shared lock. Here&#8217;s an example on how to do this.<\/p>\n<p><?php\n$fp = fopen('foo.txt', 'r');\nif(flock($fp, LOCK_SH))\n{\nwhile(!feof($fp))\n{\necho fgets($fp);\n}\nflock($fp, LOCK_UN);\n}\nfclose($fp);\n?><\/p>\n<p>Keep in mind that flock() will not work on NFS mounted filesystems or FAT filesystems.<\/p>\n<h2><\/h2>\n","protected":false},"excerpt":{"rendered":"<p>Writing to a file is easy with PHP. But what will happen if 2 processes try to write to a file at once? Exactly, your data might easily become corrupted and useless. You don&#8217;t want that to happen, of course. That&#8217;s why you need to implement file locking. flock() is your friend. For writing to&#8230;<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1,7],"tags":[],"_links":{"self":[{"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/posts\/71"}],"collection":[{"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/comments?post=71"}],"version-history":[{"count":0,"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/posts\/71\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/media?parent=71"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/categories?post=71"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.nivas.hr\/blog\/wp-json\/wp\/v2\/tags?post=71"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}