开发者

simpleXML not saving correctly the XML file

I wrote an HTTP request that mobile devices send their respective tokens to the server, an this co开发者_StackOverflow社区de on the server checks a XML file if the token was already registered. If so, it does nothing, if not, it adds the new token to the XML.

When when saving (maybe because there are many people trying to access at the same time), the xml gets truncated, like this:

<root> <token> 123456 </token> <token> 234567 </token> <token> 345678 </to

What shall be happening?

The code is something like this:

    if( !ini_get('safe_mode') ){
        set_time_limit(0);
    } 

    if (file_exists("tokens.xml")) 
    {
        $xml = simplexml_load_file("tokens.xml");       

        if ($xml)
        {
            $found = false;

            foreach($xml->children() as $child)
            {
                if ($_POST['token'] == $child) 
                {
                    $found = true;
                    break;
                }
            }
            if ($found)
                echo $_POST['token'];
            else
            {
                $xml->addChild("token", $_POST['token']);
                unlink("tokens.xml");
                $xml->saveXML("tokens.xml");
                echo $_POST['token'];
            }
        }
        else
            echo "Error";

    }


Weird error. Perhaps a race condition, in which case you should look into flock(). Actually, what you'd have to do is flock() a dummy file that serves as global lock, write the new file under a temporary name then rename the file to "tokens.xml". So basically you're implementing your own concurrency control... which is never a good sign.

Ideally, you should really use a database instead.

On a side-node, file_put_contents() is supposed to be atomic IIRC. I don't know if SimpleXMLElement::asXML() is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜