save array as binary file - php

How would I save an array to a binary file and then read that binary file back to an array in php?
This is where I am so far, but it doesn't work:
$arr = array("key1"=>"val1","key2"=>"val2","key3"=>"val3");
//save file
$file_w = fopen('binint', 'w+');
$bin_str = pack('i', $arr);
fwrite($file_w, $bin_str);
fclose($file_w);
//load file
$filename = "file.bin";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
$newarr = unpack('i*', $contents);
print_r($newarr);

Related

Finding a file with PHP

I want to find a file with a wildcard in the same directory as my index.php is.
When I assign the $file_name manually with the name string, it works fine.
<?php
$file_name = glob("*.csv");
$handle = fopen($file_name, "r");
$file = fread($handle, filesize($file_name));
fclose($handle);
echo $file;
?>
The browser should output the content of the .csv file, like when I assign the $file_name manually.
you need a loop because glob() returns an array:
foreach (glob("*.csv") as $filename) {
$handle = fopen($filename, "r");
$file = fread($handle, filesize($filename));
fclose($handle);
echo $filename;
}
This script will find some images in working folder.
<?php
$workdir = getcwd(); // my working dir
$patternTofind = ".{jpg,gif,png}"; // Images example
$files = glob("$workdir*$patternTofind", GLOB_BRACE);
// Print result found
print_r($files);
?>

Open dir from read txt

PHP script who open and search data from .txt is:
function explodeRows($data) {
$rowsArr = explode("\n", $data);
return $rowsArr;
}
function explodeTabs($singleLine) {
$tabsArr = explode("\t", $singleLine);
return $tabsArr;
}
$filename = "/txt/name.txt";
$handle = fopen($filename, 'r');
$data = fread($handle, filesize($filename));
$rowsArr = explodeRows($data);
for($i=0;$i<count($rowsArr);$i++) {
$lineDetails = explode("|",$rowsArr[$i]);
if ($kodas == $lineDetails[2]) {
$link3=$lineDetails[4];
echo "";
} }
fclose($handle);
It's works well, but now I transfer name.txt to another folder (folder name txt). How to make, first open this folder and search open name.txt
$filename = "txt/name.txt";
$handle = fopen($filename, 'r');
$data = fread($handle, filesize($filename));
$rowsArr = explodeRows($data);

Lock the file while reading and writing

I have a file which stores some value. Users can add stuff to that file and the counter in that file is updated. But if two users open the file, they'll get the same counter ($arr['counter']). What should I do? Maybe can I lock the file for one user and release the lock after he updates the counter and add some stuff back to the file? Or PHP already locks the file once is opened and I don't need to worry? Here's my current code:
$handle = fopen($file, 'r');
$contents = fread($handle, filesize($file));
fclose($handle);
$arr = json_decode($contents);
//Add stuff here to $arr and update counter $arr['counter']++
$handle = fopen($file, 'w');
fwrite($handle, json_encode($arr));
fclose($handle);
PHP has the flock function which will lock the file before writing to it, example,
$handle = fopen($file, 'r');
$contents = fread($handle, filesize($file));
fclose($handle);
$arr = json_decode($contents);
//Add stuff here to $arr and update counter $arr['counter']++
$handle = fopen($file, 'w');
if(flock($handle, LOCK_EX))
{
fwrite($handle, json_encode($arr));
flock($handle, LOCK_UN);
}
else
{
// couldn't lock the file
}
fclose($handle);

read and write file with newline php

I have a php file with the following info
One
Two
Three
Now i want to split them into an array, so i used:
$filehandle = fopen($filename, 'rb');
$line_of_text = fgets($filehandle);
$array = explode("\n", $line_of_text);
But it is not working.
They are written in the file like this:
$filehandle = fopen($textfile, 'a');
fputs($filehandle, $line . "\r\n");
fclose($filehandle);
So how do i read them into an array?.
Thanks.
I think you are looking for file(). However, it should be noted that this will leave all your array elements with a trailing CRLF sequence on them.
Alternatively (all these will strip the trailing CRLF):
$array = explode("\r\n", file_get_contents($filename));
...or...
$fp = fopen($filename, 'r');
$filecontents = fread($fp, filesize($filename));
$array = explode("\r\n", $filecontents);
...or...
$fp = fopen($filename, 'r');
$array = array();
while (($line = fgets($fp)) !== FALSE) $array[] = trim($line);
You should use the file function
file — Reads entire file into an array
$your_array = file ("filename", FILE_IGNORE_NEW_LINES); // add the flag to strip newlines

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