Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP increment specific line value

Tags:

ajax

php

I have a file called abFormStats.txt that currently looks like this:

A|0
B|0

I have an AJAX call firing to a handling page with the current "split" type (A or B). I know how to open a file and write to it, however I'm currently unsure on how to increment a specific line's value based on what "split" is being used.

Here is the code that i use to write to a file, like i say though, this just overwrites what is currently in the file, which isn't what i'm after at all:

$fp = fopen('abFormStats.txt', 'c+');
flock($fp, LOCK_EX);

$count = (int)fread($fp, filesize('abFormStats.txt'));
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, $count + 1);

flock($fp, LOCK_UN);
fclose($fp);

Not sure if you guys need it, but the is the current AJAX call:

var split = 'A';
$.ajax({
    type: 'POST',
    url: "updateStats.php",
    data: {
        "splitType": split
    },
    success: function(result){
        console.log(result);
    }
});
like image 885
Andy Holmes Avatar asked Feb 16 '26 20:02

Andy Holmes


1 Answers

How about something like this:

$filename = 'abFormStats.txt';
$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as &$line) {
    list($type, $count) = explode('|', $line, 2);

    if ($type == $_POST['splitType']) {
        $count++;
    }

    $line = "$type|$count";
}

if (file_put_contents($filename, implode("\n", $lines), LOCK_EX)) {
    // Success!
} else {
    // Error (lock, file permissions etc)
    http_response_code(503);
}

How you send the failure back to the client side is up to you (error message in body, HTTP status code etc), but if you use HTTP status code as above, then you can use jQuery's success/error callbacks to differentiate.

like image 111
cmbuckley Avatar answered Feb 19 '26 09:02

cmbuckley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!