Splitting a text file in half using PHP? - 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');

Related

Correct fread() application?

Say I'm uploading a chunked file and I have to recompose it. I know the total chunks and data from every iteration.
I founded code like this:
for ($i = 1; $i <= $num_chunks; $i++) {
$file = fopen($target_file.$i, 'rb');
$buff = fread($file, 2097152);
fclose($file);
$final = fopen($target_file, 'ab');
$write = fwrite($final, $buff);
fclose($final);
unlink($target_file.$i);
}
Apparently, the 2097152 value, has no meaning, at least to me. I read the php docs but couldn't understand too much. Could anyone explain me how I should choose that secon param of fread? And how the thing works?
The second parameter is the amount of data to read, as your reading this in one chunk you have to be sure that it is enough to process any chunk. The value you've set is 2MB, which may be enough, but you could change the code so that it reads it in smaller chunks and loops till the input is fully read.
I've also changed it to open the output file once and just write the contents as you go along...
$final = fopen($target_file, 'wb'); // Open for write and start from beginning of file
for ($i = 1; $i <= $num_chunks; $i++) {
$file = fopen($target_file.$i, 'rb');
while($buff = fread($file, 4096)) {
fwrite($final, $buff);
}
fclose($file);
unlink($target_file.$i);
}
fclose($final);

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

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)?

incrementing counter in multiple text file

I'm trying to increment a counter in a multiple text file when a user visit my page, but the code I'm working is not working below is the code
$files = glob("counters/visit/*.txt");
foreach($files as $file) {
$content = file_get_contents($file);
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$content++;
$f = fopen($files, "w");
fwrite($f, $content);
fclose($f);
}
}
First make sure that $contentis an integer by doing the following :
$content = intval(file_get_contents($file));
Then you're using :
$f = fopen($files, "w");
Instead of :
$f = fopen($file, "w");
fopen can't accept an array as parameter
Also as mentioned by #alanlittle, if you want all your files to be incremented, you should think about the moment where you set $_SESSION['hasVisited']="yes"; and put it at the end of the loop.

Read files for part by part for 1000 bytes in PHP

I want to read a file line by line and add it into a variable till its string length is 1000 bytes . The file is relatively large,
Hence, what I am doing is
if(file_exists($file)
{
$fh = fopen($file, "r");
while(!feof($fh) or strlen($chunk) < 10001)
{
$line = fgets($fh, 1000);
$chunk = $chunk."**".$line;
}
}
Issue is how does I store each chunk into an array index till I encounter end of file ?
What about this:
if(file_exists($file)
{
$fh = fopen($file, "r");
$chunks = array();
while(!feof($fh) or strlen($chunk) < 10001)
{
$line = fgets($fh, 1000);
// add line to the buffer
$chunks []= $line;
}
}
? Or am I missing something?

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