I have an issue with a processing script. I would like to allow 2 duplicate ip addresses maximum in a csv file, to prevent some spamming and to take into consideration that the user could make a mistake in form fill. I cant seem to reference the $ip variable correctly in the script, or there might be something I am missing altogether. Here is the code snippet thus far:
<?php
#VARIABLE DECLARATIONS (filename and post vars) GO HERE
$counter = 0;
if (file_exists($filename))
{
$file = fopen($filename, "a");
while($data = fgetcsv($filename)){
if(isset($data[$ip])){
$counter++;
continue;
if((isset($data[$ip])){
$counter++;
if($counter == 2){
echo "";
}
}
}
}
##file write goes here
}
?>
Any help on this would be appreciated,
Jim
You will have to read all the elements in an array first and only after you have the number of occurrences of each IP address ready, should go ahead with writing the file (a separate file may be?).
You can first prepare an array with IP indexes and all the rows corresponding to an IP as value attributes to that key. This could be done -
$csvArray = str_getcsv(file_get_contents('myCSVFile.csv'));
foreach($csvArray as $eachRow)
{
//prepare IP indexed array with every detail row as an attribute of the corresponding IP key.
$properlyFormattedArray[$eachRow[5]][] = $eachRow;
}
You get an array like this -
Array(['92.27.21.171'] =>
[0] => Array("Mr","Test","davis","07972889989","01159174767","92.27.21.171"),
[1] => Array("Mr","bob","jones","07998998008","01159174767","92.27.21.171"),
...
['92.27.21.172'] => ...
)
Once you have this array, just loop over it, and write only at max 2 rows for every IP.
foreach($properlyFormattedArray as $ip => $details)
{
$count = 0;
foreach($details as $eachDetail)
{
if($count<2)
{
//write $eachDetail into file
$count++;
}
}
}
But, in this case, the order of data (compared with your input file) will be changed, and the duplicates will be written in consecutive rows in the csv file (not sure if you would be okay with it).