Saeed Masoumi
Saeed Masoumi

Reputation: 8916

How to handle multiple request to write a file in php?

I have this code

<?php
    if (!file_exists($folderAddress . $_GET['name'] . '.json')) {
            //create file
            $myJson = fopen($folder.$_GET['name']. ".json", "w");        
            //get a context of a url 
            $ch = curl_init($myUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $text = '';
            if( ($text = curl_exec($ch) ) === false)
            {
                die('fail');
            }
            // Close handle
            curl_close($ch); 
            //copy to json file
            $result = fwrite($myJson, $text);
            fclose($myJson);
            $t = time();
           //add update date to db
            if (!mysqli_query($con, "INSERT INTO test (name )
            VALUES ('$_GET['name]', '$t')")
            ) {
            echo $text;
            mysqli_close($con);
                die('');
            }
            //show the json file
            echo $text;
        } 
?>

And i have this problem if users request this file in same time or with less than a 500 ms delay all of them think that the file does not exist. So how can i prevent users to write file when the first is writing on it ?

Upvotes: 1

Views: 1451

Answers (1)

N.B.
N.B.

Reputation: 14060

You use exclusive lock when writing to a file, so the other processes can't interfere until initial one is complete. You also don't need fopen / fwrite whatsoever. Fetch your data using cURL and use the following snippet:

file_put_contents($filename, $contents, LOCK_EX);

Upvotes: 5

Related Questions