Forum Moderators: coopster

Message Too Old, No Replies

Input a file 1 line at a time (fread)?

File to large to open at once.

         

cochranrg

9:25 pm on Apr 10, 2006 (gmt 0)

10+ Year Member



I need to open a text file and import the contents one line at a time. Is this do-able? Can't seem to figure out if it is or not.

When I do:

$filename = "../".$_GET['cat'].".dba";
$categories = fopen($filename, "r") or die("Can't Open File $filename");
$cat_file = fread($categories, filesize($filename));
fclose($categories);

I get

Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 1095 bytes) in /#*$!xxx/xxxxx/viewlist.php on line 38

Help!

Thanks,
Rob

avant_garde

5:02 am on Apr 11, 2006 (gmt 0)

10+ Year Member



Okay, first, you probably want to verify that your GET variable is safe to use and in the format you intend. You might want to make sure there are no ".", "/", or "\" characters, for example:

$cat = $_GET['cat'];
if (strpos($cat, '.')!== false ¦¦ strpos($cat, '/')!== false ¦¦ strpos($cat, '\')!== false) {
die('bad cat');
}

Second, if you want to deal with the lines of a text file one at a time, you could use the

file()
function. This will read the entire file and return it as an array, with the value of each array element corresponding to a line in the file.

$lines = file($filename);

Lastly, if you want to import data from large database type files (.dba), have a look at the Database (dbm-style) Abstraction Layer Functions chapter in the PHP manual.

adb64

7:10 am on Apr 11, 2006 (gmt 0)

10+ Year Member



You may use the following code to read a file line by line:

$fp = @fopen($filename,"r");
if ($fp)
{
while(!feof($fp))
{
$Line = trim(fgets($fp,1024));
/* handle $Line here */
}
fclose($fp);
}

Max length of a line in this case in 1024 characters, adapt to your needs.

Arjan

cochranrg

8:38 pm on Apr 13, 2006 (gmt 0)

10+ Year Member



Thank you all. Found out that my files are getting too big for the host anyway. Switching to MySQL, having problems though with that as well!

Hard to be a newbie...

RC