Write and read from the same file- PHP - php

I am trying to write to a file and then read the data from the same file. But sometimes I am facing this issue that the file reading process is getting started even before the file writing gets finished. How can I solve this issue ? How can i make file writing process finish before moving ahead?
// writing to file
$string= <12 kb of specific data which i need>;
$filename.="/ttc/";
$filename.="datasave.html";
if($fp = fopen($filename, 'w'))
{
fwrite($fp, $string);
fclose($fp);
}
// writing to the file
$handle = fopen($filename, "r") ;
$datatnc = fread($handle, filesize($filename));
$datatnc = addslashes($datatnc);
fclose($handle);

The reason it does not work is because when you are done writing a string to the file the file pointer points to the end of the file so later when you try to read the same file with the same file pointer there is nothing more to read. All you have to do is rewind the pointer to the beginning of the file. Here is an example:
<?php
$fileName = 'test_file';
$savePath = "tmp/tests/" . $fileName;
//create file pointer handle
$fp = fopen($savePath, 'r+');
fwrite($fp, "Writing and Reading with same fopen handle!");
//Now rewind file pointer to start reading
rewind($fp);
//this will output "Writing and Reading with same fopen handle!"
echo fread($fp, filesize($savePath));
fclose($fp);
?>
Here is more info on the rewind() method http://php.net/manual/en/function.rewind.php

I have mentioned the URL through which i got the solution. I implemented the same. If you want me to copy the text from that link then here it is :
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
// release lock
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);

Use fclose after writing to close the file pointer and then fopen again to open it.

Related

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

File manipulation in PHP: lock, read, clear, unlock

I want some PHP to do the following in this order:
Gain exclusive lock to a file (waiting if already locked)
Read the contents of the file
Empty the file of all contents
Remove the lock
But any code I'm coming up with one way or another always relinquishes the lock between the reading and writing.
$fp = fopen('status.txt', 'r+');
flock($fp, LOCK_EX);
$str = fread($fp,1000); // [another hack. I just want it to read everything]
unlink('status.txt');
touch('status.txt');
Any ideas? I don't trust anything I do with files.
I think ftruncate can do what you want, since it works on a file that you already have open.
http://www.php.net/manual/en/function.ftruncate.php
Here's their example:
<?php
$filename = 'lorem_ipsum.txt';
$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>
So I think what you want then is something like:
$fp = fopen('status.txt', 'r+');
flock($fp, LOCK_EX);
$str = fread($fp, filesize('status.txt'));
ftruncate($fp, 0);
flock($fp, LOCK_UN);
fclose($fp);

fwrite writes NUL

I'm trying to write to a file with PHP and this is the code I'm using (taken from this answer to my previous question):
$fp = fopen("counter.txt", "r+");
while(!flock($fp, LOCK_EX)) { // acquire an exclusive lock
// waiting to lock the file
}
$counter = intval(fread($fp, filesize("counter.txt")));
$counter++;
ftruncate($fp, 0); // truncate file
fwrite($fp, $counter); // set your data
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
fclose($fp);
The read part works fine, if the file gets read, it's content is read well, i.e. if the file contains 2289, then 2289 is read.
The problem is that when it increments and rewrites the value to that file, [NUL][NUL][NUL][NUL][NUL][NUL][NUL][NUL]1 gets written.
What am I missing? Why do null characters get written?
The thing you are missing is rewind(). Without it, after you truncate to 0 bytes, the pointer is still not at the beginning (reference). So when you write your new value, it pads it with NULL in your file.
This script will read a file (or create if it doesn't exist) for a current count, increments, and writes it back to the same file every time the page loads.
$filename = date('Y-m-d').".txt";
$fp = fopen($filename, "c+");
if (flock($fp, LOCK_EX)) {
$number = intval(fread($fp, filesize($filename)));
$number++;
ftruncate($fp, 0); // Clear the file
rewind($fp); // Move pointer to the beginning
fwrite($fp, $number); // Write incremented number
fflush($fp); // Write any buffered output
flock($fp, LOCK_UN); // Unlock the file
}
fclose($fp);
EDIT #2:
Try this with flock (tested)
If file is not locked, it will throw an Exception (see added line) if(...
I borrowed the Exception snippet from this accepted answer.
<?php
$filename = "numbers.txt";
$filename = fopen($filename, 'a') or die("can't open file");
if (!flock($filename, LOCK_EX)) {
throw new Exception(sprintf('Unable to obtain lock on file: %s', $filename));
}
file_put_contents('numbers.txt', ((int)file_get_contents('numbers.txt'))+1);
// To show the contents of the file, you
// include("numbers.txt");
fflush($filename); // flush output before releasing the lock
flock($filename, LOCK_UN); // release the lock
fclose($filename);
echo file_get_contents('numbers.txt');
?>
You can use this code, a simplified version, but am not sure if it's the best:
<?php
$fr = fopen("count.txt", "r");
$text = fread($fr, filesize("count.txt"));
$fw = fopen("count.txt", "w");
$text++;
fwrite($fw, $text);
?>

Working with huge text files in PHP?

I need to scan through a 30MB text file - it's a list of world cities - How can I access this file, I feel like a File_Get_Contents will give my server a stroke
Just fopen it and then use fgets.
Filesystem functions come handy in this situation.
Example
$filename = "your_file_path";
// to open file
$fp = fopen($filename, 'r'); // use 'rw' to open file in read/write mode
// to output entire file
echo fread($fp, filesize($filename));
// to close file
fclose($fp);
References
(some handy functions)
All Filesystem Functions
fopen() - open file
fread() - read file content
fgets() - to get line
fwrite() - write content to file
fseek() - change file pointer's position
rewind() - rewind file pointer to pos 0
fclose() - close file
...
<?php
$fh = #fopen("inputfile.txt", "r");
if ($fh) {
while (($line = fgets($fh)) !== false) {
echo $line;
// do something with $line..
}
fclose($fh);
}
?>
More information/examples on http://pt.php.net/manual/en/function.fgets.php

File Handling using PHP

Can anyone tell the method to modify/delete the contents of a text file using PHP
Using file_put_contents:
file_put_contents($filename, 'file_content');
If you want to append to the file instead of replacing it's contents use:
file_put_contents($filename, 'append_this', FILE_APPEND);
(file_out_contents is the simpler alternative to using the whole fopen complex.)
By using fopen:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
}
Write "" to a file to delete its contents.
To delete contents line by line use:
$arr = file($fileName);
unset($arr[3]); // 3 is an arbitrary line
then write the file contents. Or are you referring to memory mapped files?
There are number of ways to read files. Large files can be handled very fast using
$fd = fopen ("log.txt", "r"); // you can use w/a switches to write append text
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
you can also use file_get_contents() to read files. its short way of achieving same thing.
to modify or append file you can use
$filePointer = fopen("log.txt", "a");
fputs($filePointer, "Text HERE TO WRITE");
fclose($filePointer);
YOU CAN ALSO LOAD THE FILE INTO ARRAY AND THEN PERFORM SEARCH OPERATION TO DELETE THE SPECIFIC ELEMENTS OF THE ARRAY.
$lines = file('FILE WITH COMPLETE PATH.'); // SINGLE SLASH SHOULD BE DOUBLE SLASH IN THE PATH SOMTHING LIKE C://PATH//TO//FILE.TXT
Above code will load the file in $lines array.

Categories