2017-10-17 13 views
1

현재 뷰의 수를 계산하고 .txt 파일에 저장하는 작업 스크립트가 있습니다.페이지 방문 카운터 - 작동하지만 IP 주소별로 제한하고 싶습니다.

잘 작동하지만 IP 주소를 어떻게 제한합니까?

나는 이것을 시도했지만 그것은 중요하지 않다.

// Get filename of Page 
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php'); 
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']); 

// Remove .php extension 
$counterName = basename($pageName, ".php").".txt"; 

// Open the file for reading 
// "a+" Read & write the file. Create file if not exist. 
$fp = fopen($counterName, "a+"); 
$fpIP = fopen("ip_".$counterName, "a+"); 

fwrite($fpIP, $ip."-"); 

// Get the existing count 
$count = fread($fp, 1024); 

// Close the file 
fclose($fp); 

// Add 1 to the existing count 
$count = $count + 1; 

// Reopen the file and erase the contents 
$fp = fopen($counterName, "w"); 

$ipRead = file_get_contents('ip_index.txt'); 

if(strpos($ipRead, "$ip") !== FALSE) { 
    echo $count; 
} 
else { 
    fwrite($fp1, $count); 
    echo $count;  
} 
fclose($fp); 

다음은 그들이 자신의 IP 주소를 기반으로 페이지에왔다 얼마나 많은 시간을 각 개별 방문자를 표시합니다 Barmar의 코드 (완전 작업) 내 업데이트 된 코드입니다.

// Get filename of Page 
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php'); 

// Remove .php extension 
$counterName = basename($pageName, ".php").".counter"; 

// Get IP 
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']); 


$count_text = @file_get_contents($counterName); 
$counters = $count_text ? json_decode($count_text, true) : array(); 
if (isset($counters[$ip])) { 
    $counters[$ip]++; 
} else { 
    $counters[$ip] = 1; 
} 
file_put_contents($counterName, json_encode($counters)); 
echo $counters[$ip]; 
+0

파일에 개수를 저장하는 특별한 이유가 있습니까? 또한 $ ip를 echo하는 경우 값은 무엇입니까? – kyle

+0

IP를 파일 이름에 넣거나 IP가 키로 연결된 연관 배열을 파일에 넣어야합니다. – Barmar

답변

0

카운터 파일에 $ip을 입력하지 않은 연관 배열을 저장하십시오.

$count_text = @file_get_contents($counterName); 
$counters = $count_text ? json_decode($count_text, true) : array(); 
if (isset($counters[$ip])) { 
    $counters[$ip]++; 
} else { 
    $counters[$ip] = 1; 
} 
file_put_contents($counterName, json_encode($counters)); 
echo $counters[$ip]; 

이 디자인에는 ip_XXX.txt 파일이 필요하지 않습니다.

+0

도움을 주셔서 감사합니다. 거의 다 왔지만 스크립트에 다음 오류가 표시됩니다. 경고 : ****/test/index.php의 배열로 스칼라 값을 사용할 수 없습니다. 29 행 위 코드를 업데이트했습니다. – Ravenholm

+0

어떤 줄이 오류가 발생합니까? – Barmar

+0

편집을 취소했습니다. 새 코드를 표시하고 추가로 추가하려면 해당 질문에 대한 원래 코드를 제거하지 마십시오. – Barmar