Provided the following example code:
<?php
$handle = fopen("/tmp/test_file/sometestfile", "r");
$contents = '';
while (!feof($handle)) {
$contents = fread($handle, 10);
print $contents;
sleep(1);
}
fclose($handle);
?>
If sometestfile, which is a txt file in my case, changes during the read loop, why is the php program continuing to read from the old file?
Say it is full of 1's and I cat sometestfile_new over it which is full of 2's.
I am running this on Linux, is this inode related?
If rewind() is added after each loop, the new file will be read instead, after the overwrite point in time.
from php.net
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
fopen() binds a named resource, specified by filename, to a stream.
the fopen() as soon as it's called it "caches" the file and will output in the method you mention, example is your $contents = fread($handle, 10);
You can delete the file and it will still read that resource until it finishes the file !feof($handle)
You cannot do anything else with fopen(), you just can't reread the source and continue to print it.
Related
$fh = fopen(PATH_TO_FILE, "r+");
flock($fh, LOCK_EX);
$data = fgets($fh);
$data = json_decode($data, true);
$data['mod_1'] = 1;
$data_write = json_encode($data);
ftruncate($fh, 0);
fwrite($fh , $data_write);
clearstatcache();
flock($fh, LOCK_UN);
fclose($fh);
This works only if I prepare JSON file by myself. The problem is, next time I try to call this method, json_decode() returns false and the file is partial corrupted. json_decode() can not parse it anymore.
What is the problem with this code?
My JSON File contents:
{"mod_1":0,"mod_2": 0}
All I want is to read file, modify its content and write back to file(overwrite). I must use LOCK_EX, so I assume file_put_contents is not for me.
The problem was that ftruncate didn't set the pointer at the beginning of empty file. So I added rewind($fh) right after ftruncate and the problem was solved.
Solved! I used an existing json file that I was using to display diagrams on the page.
I have a 2000 line text file. I want to read in the first 3000 bytes to a php variable. This works, but only at the cost of reading in the entire text file:
$little_diagrams = ('assets/diagrams.txt'); $mason = file($little_diagrams);
I tried this, but it doesn't work. Any ideas on why?
$little_diagrams = file_get_contents("assets/diagrams.txt", NULL, NULL, 0, 3000);
$mason = file($little_diagrams);
The trouble is that I have to process lines in "assets/diagrams.txt" such as:
2833|6979|Poloskov|||Nikolayev|Igor|2272|1n3rk1/3p1ppp/5q2/2p1P3/2B2P2/r2Q2P1/1b2N2P/1R3K1R|
2832|6979|Poloskov|||Nikolayev|Igor|2272|r2qk2r/1b1p1ppp/n4b2/2pN4/2B1P3/8/PP3PPP/R2QK1NR|
2831|6978|Nikolayev|Igor|2272|Buturin|Vladimir (IM)|2405|r3r1k1/1ppb1pp1/3p1n1p/2nP4/p3P3/4NP2/PPBN1KPP/R3R3|
2830|6978|Nikolayev|Igor|2272|Buturin|Vladimir (IM)|2405|r2qr1k1/1ppb1pp1/p1np1n1p/8/3PP3/4NN2/PPB2PPP/R2Q1RK1|
2829|6977|Nikolayev|Igor|2272|Tabatadze|Tamaz|2288|2rqk2r/4bp1p/p1n1b3/3pP3/Pp1P2p1/1P3p2/1B2NPPP/2RQNRK1|
2828|6976|Lutsko|Igor|2307|Nikolayev|Igor|2272|6r1/1pp2p1k/p2p3p/2bP4/2P2r2/1P4NP/P2R1P1K/5R2|
NEW CODE: (doesn't work, no diagrams are displayed at http://communitychessclub.com/ left column bottom)
$filename = "assets/diagrams.txt";
$handle = fopen($filename, "r");
$little_diagrams = fread($handle, 3000); //<<--- as per your need
fclose($handle);
$X = 5000; $line = 0;
foreach($little_diagrams as $line) {$X++; if ($X >= 5040) {break;} $token = explode("|", $line); //etc
}
<?php
$filename = "c:\\files\\yourfile.txt";
$handle = fopen($filename, "rb");
//$little_diagrams = fread($handle, filesize($filename));
$little_diagrams = fread($handle, 3000); //<<--- as per your need
fclose($handle);
?>
Try above code and read this fread function documentation
I hope this will help also see the example code Example #2 Binary fread() example
fread takes two arguments
string fread ( resource $handle , int $length )
second is length part
length bytes have been read as per documentation
fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:
UPDATED BELOW
Note:
You can use file_get_contents() to return the contents of a file as a string.
change second argument to FALSE from NULL then try hope it will work
so in my opinion correct code will be like below take a try
<?php
//however working with null also
$file_content =file_get_contents('demoTest.txt',FALSE,NULL,0,3000);
echo 'File Size: '.filesize('demoTest.txt');
echo '<br/> CONTENT HERE<br />'.$file_content;
echo '<br /><br />String Length: '.strlen($file_content);
?>
read the documentation at here for file function
I need to read the content of a single file, "test.txt", inside of a zip file. The whole zip file is a very large file (2gb) and contains a lot of files (10,000,000), and as such extracting the whole thing is not a viable solution for me. How can I read a single file?
Try using the zip:// wrapper:
$handle = fopen('zip://test.zip#test.txt', 'r');
$result = '';
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
echo $result;
You can use file_get_contents too:
$result = file_get_contents('zip://test.zip#test.txt');
echo $result;
Please note #Rocket-Hazmat fopen solution may cause an infinite loop if a zip file is protected with a password, since fopen will fail and feof fails to return true.
You may want to change it to
$handle = fopen('zip://file.zip#file.txt', 'r');
$result = '';
if ($handle) {
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
}
echo $result;
This solves the infinite loop issue, but if your zip file is protected with a password then you may see something like
Warning: file_get_contents(zip://file.zip#file.txt): failed to open
stream: operation failed
There's a solution however
As of PHP 7.2 support for encrypted archives was added.
So you can do it this way for both file_get_contents and fopen
$options = [
'zip' => [
'password' => '1234'
]
];
$context = stream_context_create($options);
echo file_get_contents('zip://file.zip#file.txt', false, $context);
A better solution however to check if a file exists or not before reading it without worrying about encrypted archives is using ZipArchive
$zip = new ZipArchive;
if ($zip->open('file.zip') !== TRUE) {
exit('failed');
}
if ($zip->locateName('file.txt') !== false) {
echo 'File exists';
} else {
echo 'File does not exist';
}
This will work (no need to know the password)
Note: To locate a folder using locateName method you need to pass it like folder/ with a
forward slash at the end.
As I start the process of writing my site in PHP and MySQL, one of the first PHP scripts I've written is a script to initialize my database. Drop/create the database. Drop/create each of the tables. Then load the tables from literals in the script.
That's all working fine! Whoohoo :-)
But I would prefer to read the data from files rather than hard-code them in the PHP script.
I have a couple of books on PHP, but they're all oriented toward web development using MySQL. I can't find anything about reading and writing to ordinary files.
Yes, I know there's a gazillion questions here on stackoverflow about reading TXT files, but when I look at each one, they're for C or C# or VB or Perl. I'm beginning to think that PHP just can't read files :-(
All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:
program readfile;
handle = open('myfile.txt');
data = read (handle);
while (not eof (handle)) begin
display data;
data = read (handle);
end;
close (handle);
end;
I will also need to write files on the server when I get to the part of my site where people upload avatars, and save them as JPG or GIF files. But that's for later.
Thanks!
From the PHP manual for fread():
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
EDIT
per the comment, you can read a file line by line with fgets()
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:
echo file_get_contents('/path/to/file.txt');
Yes that brief, see file_get_contents, you normally don't need a loop:
$file = new SPLFileObject('/path/to/file.txt');
foreach($file as $line) {
echo $line;
}
Well, since you're asking about resources on the subject, there's a whole book on it in the PHP.net docs.
A basic example:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Why you not read php documentation about fopen
$file = fopen("source/file.txt","r");
if(!file)
{
echo("ERROR:cant open file");
}
else
{
$buff = fread ($file,filesize("source/file.txt"));
print $buff;
}
file_get_contents does all that for you and returns the text file in a string :)
You want to read line by line? Use fgets.
$handle = #fopen("myfile.txt", "r");
if ($handle) {
while (($content = fgets($handle, 4096)) !== false) {
//echo $content;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
<?php
$handle = fopen("https://graph.facebook.com/search?q=mark&type=user&access_token=2227470867|2.mLWDqcUsekDYZ_FQQXYnHw__.3600.1279803600-100001317997096|YxS1eGhjx2rpNYLNE9wLrfb5hMc.", "r");
echo $handle;
?>
Why does it echo Resource id #4 instead of the page itself?
Because fopen() returns a resource pointer to the file, not the content of the file. It simply opens it for subsequent reading and/or writing, dependent on the mode in which you opened the file.
You need to fread() the data from the resource referenced in $handle.
This is all basic stuff that you could have read for yourself on the manual pages of php.net
Once you have created your $handle you now need to fread() the contents.
$contents = '';
while (!feof($handle))
{
$contents .= fread($handle, 8192);
}
fclose($handle);
echo $contents;
source: php.net/manual/en/function.fread.php
Use
<?php
$data = file_get_contents("https://graph.facebook.com/search?q=mark&type=user&access_token=2227470867|2.mLWDqcUsekDYZ_FQQXYnHw__.3600.1279803600-100001317997096|YxS1eGhjx2rpNYLNE9wLrfb5hMc.", "r");
echo $data;
?>
Because fopen return the resource handle of the file it opened not the contents.