Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Dec 2004
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Reading more than 1 file with file_get_contents

    I use this script to read a text file and add it to a database.

    PHP Code:
    <?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:

    Code:
    root dir
    
    folder1
    iplista.txt
    iplistb.txt
    
    folder2
    
    iplist1.txt
    iplist2.txt

  • #2
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    You could always wrap it in a function:

    PHP Code:
    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.

    PHP Code:
    $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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •