...

View Full Version : Reading more than 1 file with file_get_contents



I3arry
01-23-2007, 02:11 PM
I use this script to read a text file and add it to a database.


<?php

include ("config.php");

if ( !$iplistTXT = file_get_contents ( "iplist.txt" ) )
{
echo"Error, file is empty";
}
else
{
$ipArray = explode( "\n", $iplistTXT);
$arraysize = sizeof($ipArray) -1;

for ( $i = 0; $i < $arraysize; $i++)
{
$ipArray[$i] = explode ( "\t", $ipArray[$i] );

$name = str_replace ( "'", "\'", trim($ipArray[$i][0]) );
$ip = trim($ipArray[$i][1]);

mysql_query("INSERT IGNORE INTO ipinfo(name,ip) VALUES('".$name."','".$ip."')") or die(mysql_error());
}
}
?>

I'd like to be able to have it read text files with other names that are located in other folders.

Such as:


root dir

folder1
iplista.txt
iplistb.txt

folder2

iplist1.txt
iplist2.txt

aedrin
01-23-2007, 04:14 PM
You could always wrap it in a function:



function readIpFile($filename) {
if ( !$iplistTXT = file_get_contents ( $filename ) ) {
echo"Error, file is empty";
} else {
$ipArray = explode( "\n", $iplistTXT);
$arraysize = sizeof($ipArray) -1;

for ( $i = 0; $i < $arraysize; $i++) {
$ipArray[$i] = explode ( "\t", $ipArray[$i] );

$name = str_replace ( "'", "\'", trim($ipArray[$i][0]) );
$ip = trim($ipArray[$i][1]);

mysql_query("INSERT IGNORE INTO ipinfo(name,ip) VALUES('".$name."','".$ip."')") or die(mysql_error());
}
}
}

readIpFile('iplist.txt');


etc.

And if you want to automatically load all files from a folder, then you should use opendir and readdir.



$dh = opendir('iplists');
while ( ($file = readdir($dh)) !== false) {
if ($file == '.' || $file == '..') continue;
readIpFile($file);
}


You could enhance it further to also recursively read into sub folders using is_dir(), but that might not be a good idea.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum