Reputation: 91
I'm creating a hit counter. The script that registers that the visitor was there creates a .txt file like this
IP Adress:127.0.0.1
Timestamp:1400602795
User Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Times visited:1
I want to be able to got information like timestamp and times visited. One way i'd like to do this is to create an array seperated by ":".
I tried to create the array, But for some reason "Times Visited" does not get included in the array. Here is the code from that attempt:
$fileResource = @fopen("hits/".$_SERVER["REMOTE_ADDR"].".txt","r");
$fileContent = @fread($fileResource,100000);
$array = preg_match_all("/(.*):(.*)\\n/i",$fileContent,$fileMatches);
//0 = IP
//1 = Timestamp
//2 = User Agent
//3 = Times Visited
echo $fileMatches[0][3];
this is the output when i try print_r($fileMatches)
Array
( [0] => Array ( [0] => IP Adress:127.0.0.1
[1] => Timestamp:1400604101
[2] => User Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
)
[1] => Array
(
[0] => IP Adress
[1] => Timestamp
[2] => User Agent
)
[2] => Array
(
[0] => 127.0.0.1
[1] => 1400604101
[2] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
)
)
Upvotes: 0
Views: 48
Reputation: 74655
If you have already read the entire contents of the file into a string, you could use explode
twice like this:
$s = <<<EOT
IP Address:127.0.0.1
Timestamp:1400602795
User Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Times visited:1
EOT;
$arr = array();
foreach (explode("\n", $s) as $line) {
if (trim($line) !== '') { // check for empty line
list($key, $value) = explode(':', $line);
$arr[$key] = trim($value);
}
}
print_r($arr);
Which creates an array like this:
Array (
[IP Address] => 127.0.0.1
[Timestamp] => 1400602795
[User Agent] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
[Times visited] => 1
)
Alternatively, instead of using fread
you could use fgets
to read each line one by one, and replace the foreach
loop with something like while (fgets($fileResource))
Upvotes: 1