fread: read until "end of line" (do not cut off lines) - php

I would like to read a file until X bytes. But the last line should be NOT cut off like in my current code:
$file = fopen("test.txt", "r");
while(! feof($file)) {
$contents = fread($file,10000);
Right now, fread reads until 10000 bytes are reached. Then cuts the line off and creates a new file. The line basically is completely stores but is split into two files. I dont want do only stop and the end of a line.
Any solutions? Thanks!

I think I got it:
$file = fopen("test.txt", "r");
while(! feof($file)) {
$contents = fread($file,$eachFileSize);
$contents = $contents . fgets($file);
Can someone confirm this is the intended way (e.g. LawrenceCherone suggested)?

Related

How to remove specific line from CSV file by its line number?

I'm trying to delete one line from CSV file by its line number, which I get as a parameter in URL.
I saw some discussions here, but it was mainly "delete a line by its id stored in first column" and so on. I tried to make it in the same way as others in these discussions, but it does not work. I only changed the condition.
if (isset($_GET['remove']))
{
$RowNo = $_GET['remove']; //getting row number
$row = 1;
if (($handle = fopen($FileName, "w+")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
//Here, I don't understand, why this condition does not work.
if ($row != $RowNo)
{
fputcsv($handle, $data, ';');
}
$row++;
}
fclose($handle);
}
}
I supposed, that it should work for me too, BCS just condition was changed. But it does not. It clears the whole file. Could you help me with it, please?
Thank you very much for any advice. Daniel.
You could load the file as an array of lines by using file().
Then remove the line and write the file back.
// read the file into an array
$fileAsArray = file($FileName);
// the line to delete is the line number minus 1, because arrays begin at zero
$lineToDelete = $_GET['remove'] - 1;
// check if the line to delete is greater than the length of the file
if ($lineToDelete > sizeof($fileAsArray)) {
throw new Exception("Given line number was not found in file.");
}
//remove the line
unset($fileAsArray[$lineToDelete]);
// open the file for reading
if (!is_writable($fileName) || !$fp = fopen($fileName, 'w+')) {
// print an error
throw new Exception("Cannot open file ($fileName)");
}
// if $fp is valid
if ($fp) {
// write the array to the file
foreach ($fileAsArray as $line) {
fwrite($fp, $line);
}
// close the file
fclose($fp);
}
If you have a unix system you could also use sed command:
exec("sed -e '{$lineToDelete}d' {$FileName}");
Remember cleaning command parameters if user input used:
https://www.php.net/manual/de/function.escapeshellcmd.php
Option if your CSV can fit to memory:
// Read CSV to memory array
$lines = file($fileName, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
// Remove element from array
unset($lines[$rowNo - 1]); // Validate that element exists!
// Rewrite your CSV file
$handle = fopen($fileName, "w+");
for ($i = 0; $i < count($lines); $i++) {
fputcsv($handle, $data, ';');
}
fclose($handle);
Option if your CSV can not fit to memory:
Use code from question, just write to separate file and later replace it with actual file:
$handle = fopen($FileName, "r");
// Read file wile not End-Of-File
while (!feof($fn)) {
if ($row != $RowNo) {
file_put_contents($FileName . '.tmp', fgets($fn), FILE_APPEND);
}
$row++;
}
fclose($handle);
// Remove old file and rename .tmp to previously removed file
unlink($FileName);
rename($FileName . '.tmp', $FileName);

PHP - Base64 Encode big files and write back synchronously

I need to base64 encode big file with PHP.
file() and file_get_contents() are not options since them loads whole file into memory.
I got idea to use this:
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
fclose($handle);
}
SOURCE: Read and parse contents of very large file
This working well for reading, but is it possible to do it like this:
Read line -> base64 encode -> write back to file
And then repeat for each line in file.
Would be nice if it could do it directly, without need to write to temporary file.
Base64 encodes 3 bytes of raw data into 4 bytes on 7-bit safe text. If you feed it less than 3 bytes padding will occur, and you can't have that happen in the middle of the string. However, so long as you're dealing in multiples of 3 you're golden, sooo:
$base_unit = 4096;
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fread($handle, $base_unit*3)) !== false) {
echo base64_encode($buffer);
}
fclose($handle);
}
http://en.wikipedia.org/wiki/Base64#Examples

Fopen problems in php

In PHP im creating a tool to open txt file with an integer in it, increment the number, save the number to a variable and then save and close the file. this is the code i have for it and it doesnt seem to work when i have it on my test server. Can anyone clue me in as to why this isnt working properly?
//opens pclnumber.txt to $handle, saves number to $number, Increments number in text file, saves and closes file
$handle = fopen("pclnumber.txt", "w+");
$number = fread($handle);
fwrite($handle, $number+1);
fclose($handle);
over all you must set reading permission on your file, and than you can use the follow code:
$filename = "pclnumber.txt";
//read file content
$handle = fopen($filename, "r");
$number = fread($handle, sizeof($filename));
fclose($handle);
//update file content
$handleWrite = fopen($filename, "w+");
fwrite($handleWrite, $number+1);
fclose($handleWrite);
Bye,
Marco

Splitting a text file in half using PHP?

I want to take one text file, split it in half, and put one half in one file, then the remaining half in the next. How would one accomplish this?
an example would be: split.php?n=file.txt
$file = $_GET['n'];
$i = 1;
$fp = fopen("./server/php/files/".$file,'a+');
$fs = filesize("./server/php/files/".$file);
$lengthhalf = $fs / 2;
while(! feof($fp)) {
$contents = fread($fp,$lengthhalf);
file_put_contents('./server/php/files/[2]'.$file,$contents);
$i++;
}
This does the work, without reading the whole file (or half of it) at once in memory:
function split_in_halves($file, $half1, $half2) {
$size = filesize($file);
$fd = fopen($file, 'rb');
stream_copy_to_stream($fd, fopen($half1, 'wb'), $size/2);
stream_copy_to_stream($fd, fopen($half2, 'wb'));
}
split_in_halves('foo', '[1]foo', '[2]foo');

How do I prepend file to beginning?

In PHP if you write to a file it will write end of that existing file.
How do we prepend a file to write in the beginning of that file?
I have tried rewind($handle) function but seems overwriting if current content is larger than existing.
Any Ideas?
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
$filename = "log.txt";
$file_to_read = #fopen($filename, "r");
$old_text = #fread($file_to_read, 1024); // max 1024
#fclose(file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
Another (rough) suggestion:
$tempFile = tempnam('/tmp/dir');
$fhandle = fopen($tempFile, 'w');
fwrite($fhandle, 'string to prepend');
$oldFhandle = fopen('/path/to/file', 'r');
while (($buffer = fread($oldFhandle, 10000)) !== false) {
fwrite($fhandle, $buffer);
}
fclose($fhandle);
fclose($oldFhandle);
rename($tempFile, '/path/to/file');
This has the drawback of using a temporary file, but is otherwise pretty efficient.
When using fopen() you can set the mode to set the pointer (ie. the begginng or end.
$afile = fopen("file.txt", "r+");
'r' Open for reading only; place
the file pointer at the beginning of
the file.
'r+' Open for reading and
writing; place the file pointer at the
beginning of the file.
$file = fopen('filepath.txt', 'r+') or die('Error');
$txt = "/n".$string;
fwrite($file, $txt);
fclose($file);
This will add a blank line in the text file, so next time you write to it you replace the blank line. with a blank line and your string.
This is the only and best trick.

Categories