MasterOfDesaster
MasterOfDesaster

Reputation: 171

Read file to slow when refreshing page multiple times

$myfile = fopen("lastupdate.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("lastupdate.txt")); fclose($myfile);

This is my php code in my wordpress Plugin. When I update the Website 20 times it tooks around 20 Seconds to load the single page. Without these 3 lines of code it only tooks 1 second to load the page.

Can you tell me why it is so slow ?

I want to use the textfile to store a string (2000 chars). In my tests there is only a "hello world" inside and it still tooks one second. How can i resolve this problem ?

Thank you very much.

Upvotes: 2

Views: 1329

Answers (1)

Akshay Hegde
Akshay Hegde

Reputation: 16997

If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

In current context,

<?php
  $myfile = fopen("lastupdate.txt", "r") or die("Unable to open file!");
  echo fread($myfile,filesize("lastupdate.txt"));
  fclose($myfile);
?>

Can be replaced with readfile(),this will read the file and send it to the browser in one command

<?php
   readfile("lastupdate.txt");
?>

This is essentially the same as

<?php
   echo file_get_contents("lastupdate.txt");
?>

except that file_get_contents() may cause the script to crash for large files, while readfile() won't.

Upvotes: 2

Related Questions