cheunology
cheunology

Reputation: 41

Why isn't my fread working?

Together is a program that is meant to look into a "csv" file with holidays in it, allow someone to choose a button labeled a number, and then write to file the holiday randomly chosen. It isn't working. Any help? Specifically the "choose.php" isn't working and isn't recieving any errors when I enable the ini_set settings, etc.

HTML FILE:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function start(){
    $.ajax({
        url:"cgi-bin/php/holiday/start.php",
        success:function(code){
            $("div#content").html(code);
        }
    }); 
}
function choose(link){
    var data_id = $(link).attr('rel');
    var post = {
        id : data_id
    }
    $.ajax({
        url:"cgi-bin/php/holiday/choose.php",
        data:post,
        method:"POST",
        success:function(code){
            $("div#content").html(code);
        }
    }); 
}
$(document).ready(function(){
    start();
});
</script>
</head>
<body>
<header id='header'></header>
<div id='content'></div>
<div id='footer'></div>
</body>
</html>

start.php

<?php
$row = 1;
if (($handle = fopen("csv/index.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p>There are {$num} choices left</p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        ?><button onClick='choose(this);' class='choice' rel='<?php echo $c;?>'><?php echo $c;?></div><?php
    }
  }
  fclose($handle);
}?>

choose.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$file = fopen("csv/index.csv","r");
$holidays = explode(',',fread($file));
fclose($file);
shuffle($holidays);
$file = fopen("csv/choices.csv","a");
$holiday = $holidays[$_GET['rel']];
fwrite($file, "MY NAME GOT " . {$holiday});
fclose($file);
unset($holidays[$_POST['rel']]);
$file = fopen("csv/index.csv","w");
fwrite($file,implode(",",$holidays);
fclose($file);
echo "YOU GOT {$holiday}";

?>

csv/index.php

christmas,chinese new year

csv/choices is empty

Upvotes: 0

Views: 762

Answers (1)

Barmar
Barmar

Reputation: 782653

fread() requires a second argument, the number of bytes to read. If you want to read the whole file, you can use the filesize() function:

$holidays = explode(',',fread($file, filesize($file)));

But if you want to read an entire file, you can use file_get_contents().

$holidays = explode(',', file_get_contents("csv/index.csv"));

And you can rewrite the file with:

file_put_contents("csv/index.csv", implode(',', $holidays));

Upvotes: 1

Related Questions