phpajaxcounterundefined-index

(PHP, AJAX) Simple counter. Figured the problem, no solution


Apologies for having to ask. In short I'm making a simple imageboard with a "like" button for each image. The number of clicks (likes) stores in 'counter.txt' file in the following format:

click-001||15
click-002||7
click-003||10

Clicking the buttons initiates a small php code via AJAX. counter.php:

<?php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
    $line = explode('||', fgets($fh));
    $item = trim($line[0]);
    $num = trim($line[1]);
    if(!empty($item)){
        if($item == $id){
            $num++; // increment count by 1
            echo $num;
            }
        $lines .= "$item||$num\r\n";
        }
    } 
file_put_contents($file, $lines);
fclose($fh);

?>  

So when I run the website and testclick my buttons I get the following message:

Notice: Undefined offset: 1 in C:\wamp64\www\wogue\counter.php on line 18

I figured that the script 'counter.php' creates a whitespace on a new string in 'counter.txt' and so it fails to 'explode' and thus make a [1] index. The way I figured that is by backspacing the last empty line in .txt file and saving it. It ran without errors until I clicked a button a few times then the same error appeared.

The piece of code in index looks like this:

<?php 
$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
    $tmp = explode('||', $line);
    $count[trim($tmp[0])] = trim($tmp[1]);
    }
?>

Any ideas?..


Solution

  • Trim $line and if it is not empty - do what you need:

    $line = trim(fgets($fh));
    if ($line) {
        $line = explode('||', $line);
        $item = trim($line[0]);
        $num = trim($line[1]);
        if(!empty($item)){
            if($item == $id){
                $num++; // increment count by 1
                echo $num;
            }
            $lines .= "$item||$num\r\n";
        }
    } 
    

    Or check with empty this way:

    $line = explode('||', fgets($fh));
    if(!empty(line[0]) && !empty($line[1])){
        if(line[0] == $id){
            $line[1]++; // increment count by 1
            echo $line[1];
        }
        $lines .= "{$line[0]}||{$line[1]}\r\n";
    }
    }