如何处理在php中写入文件的多个请求?

Sae*_*umi 1 php

我有这个代码

<?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;
        } 
?>
Run Code Online (Sandbox Code Playgroud)

我有这个问题,如果用户同时请求此文件或延迟少于500毫秒,所有人都认为该文件不存在.那么我怎样才能阻止用户在第一次写文件时写文件呢?

N.B*_*.B. 5

在写入文件时使用独占锁定,因此其他进程在初始化过程完成之前不会发生干扰.你也不需要fopen/ 无论如何fwrite.使用cURL获取您的数据并使用以下代码段:

file_put_contents($filename, $contents, LOCK_EX);
Run Code Online (Sandbox Code Playgroud)