<?php

    /**
     * The function can be used to extract information from the RIPE whois database
     * about an ip address. The function is capable of filtering the data to supply
     * you with only the information that you want. Further more it can return an
     * array with each part of the information in a seperate key or return a string
     * with all the requested information.
     *
     * @author Gerard Klomp <glj.klomp@googlemail.com>
     * @version 1.0
     * @param string $sIpAddress The ip address to retrieve more information about
     * @param boolean $bReturnArray Set to true to return an array, else it will return a string (default: true)
     * @param array $aGetValuesOf Lists all the keys to retrieve
     * @return array|string|boolean Returns array|string on success, else false
     */

    function ripe_whois($sIpAddress, $bReturnArray = true, $aGetValuesOf = array('inetnum', 'netname', 'descr', 'country', 'org')) {
        
        $rConnection = fsockopen('whois.ripe.net', 43, $iErrNo, $sErrStr, 5);
        
        if ($rConnection) {
            
            $aReturn = array();
            $sResult = '';
            
            fwrite($rConnection, $sIpAddress . "\n");
            
            while (true) {
            
                if (strlen(($sData = fread($rConnection, 8192))) == 0) {
                    break;    
                }
                
                $sResult .= $sData;
                    
            }
            
            fclose($rConnection);
            
            foreach(explode("\n", $sResult) as $sResultRow) {
            
                $sResultRow = trim($sResultRow);
                
                if (ereg('%', $sResultRow) === false && !empty($sResultRow) && ereg(implode('|', $aGetValuesOf) . ':', $sResultRow) !== false && $bReturnArray) {
                    $aRow = explode(':', $sResultRow, 3);
                    $aReturn[$aRow[0]] = (isset($aReturn[$aRow[0]]) ? $aReturn[$aRow[0]] . "\n" . trim($aRow[1]) : trim($aRow[1]));
                    $aReturn[$aRow[0]] = (isset($aRow[2]) ? $aReturn[$aRow[0]] . ":" . trim($aRow[2]) : $aReturn[$aRow[0]]);
                } else if (ereg('%', $sResultRow) === false && !empty($sResultRow) && ereg(implode('|', $aGetValuesOf) . ':', $sResultRow) !== false && !$bReturnArray) {
                    $aReturn[md5($_SERVER['REMOTE_ADDR'])] .= "\n" . $sResultRow;    
                }
                    
            }
            
            return ($bReturnArray ? $aReturn : trim($aReturn[md5($_SERVER['REMOTE_ADDR'])]));
            
        }
        
        return false;
        
    }