Problems with file_put_contents ()

1

I have a script that runs every time a particular page loads.

Basically, it does a search in the database and saves the values in a file:

$servicos = $db->prepare('SELECT id_servico, UNIX_TIMESTAMP(data) dia, user, cliente, situacao FROM servicos);
$servicos->execute(array());
$servicos_result = $servicos->fetchAll(PDO::FETCH_OBJ);

$out = array();
foreach($servicos_result as $row) {
    $out[] = array(
        'id' => $row->id_servico,
        'user' => $row->loja,
        'cliente' => $row->cliente,
        'situacao' => $row->situacao,
        'start' => $row->dia . '000',
        'end' => $row->dia . '000'
    );
}

$stringData = json_encode(array('success' => 1, 'result' => $out));
file_put_contents ( "events.json.php" , $stringData );

The problem is that it has taken some time for the file to be updated after some change in the database. That is: it is not updated the first time the page is recalled, but only after a few minutes and attempts.

The file is about 400kb.

Can this be a limitation of the server?

    
asked by anonymous 25.11.2016 / 18:39

1 answer

3

If you do not really need to cache to disk, it is much easier to use a simple echo, and write the file itself as events.json.php :

$servicos = $db->prepare('SELECT id_servico, UNIX_TIMESTAMP(data) dia, user, cliente, situacao FROM servicos);
$servicos->execute(array());
$servicos_result = $servicos->fetchAll(PDO::FETCH_OBJ);

$out = array();
foreach($servicos_result as $row) {
    $out[] = array(
        'id' => $row->id_servico,
        'user' => $row->loja,
        'cliente' => $row->cliente,
        'situacao' => $row->situacao,
        'start' => $row->dia . '000',
        'end' => $row->dia . '000'
    );
}

echo json_encode(array('success' => 1, 'result' => $out));

It would make sense for you to write to a file if it were an application that was very much accessed, and little changed, but for smaller volumes of access, or larger changes, serving the data directly from the DB is not a problem.

But note that if you use this strategy in the future, save in DB, avoid the .php extension, otherwise you will pass the PHP parser at random.

In your case, apparently the delay was in the browser's cache, not the file's recording. One solution would be to set up a folder on the Web server with a completely different cache rule, but if the above solution suffices, it is much more practical.

    
25.11.2016 / 19:30