I have a script which writes in the file in the directory where the script is. What I'm trying to do is to terminate/exit the program when the filesize reach 1MB.
What I have is
$total = 150;
$filename = "myFile.txt";
$fp = fopen($filename, 'a');
for ($i = 0; $i < $total; $i++) {
$test = [];
foreach ($characters as $field => $value) {
$test[$field] = $value;
}
if (!fwrite($fp, implode($test))) {
echo "Can't write to file: ($filename)";
exit;
}
}
What I tried is
$maxSize = 1000000; // 1 MB
$currentSize = 0; // 0 MB
$total = 150;
$filename = 'myFile.txt';
for ($i = 0; $i < $total; $i++) {
$test = [];
foreach ($characters as $field => $value) {
$test[$field] = $value;
}
if ( $currentSize < $maxSize ) {
if (!fwrite($fp, implode($test))) {
echo "Can't write to file: ($filename)";
$currentSize = filesize($filename);
exit;
}
} else {
echo "Max size of file reached\n";
exit;
}
}
Basically I have added an if condition around the fwrite function and inside I have assign filesize to $currentSize which then check against $maxSize: $currentSize = filesize($filename);.
The script doesn't stop when the filesize is reached. I'm not sure why and if this is the right way of this.