John Smith
John Smith

Reputation: 6207

Php, cache system with file_get_contents, file_put_contents: thread safe?

Symfony and other framework uses cache system, they just put a file somewhere. But if its a very heavily used site, wont it be collisions? Two file_put_contents at the same time? How to make it safer?

Upvotes: 1

Views: 451

Answers (1)

Philipp
Philipp

Reputation: 15629

You could use flock to create an lock on the given file. This would help you that no two process write on the same file.

Example from the docs:

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?> 

Upvotes: 1

Related Questions