PHP增加1个问题

时间:2014-10-11 23:29:04

标签: php

$ip = $_SERVER['REMOTE_ADDR'];                       //get IP
$referer = $_SERVER['HTTP_REFERER'];                 //get referer
$time = time();                                      //extracting timestamp
$date = date('d-m-y H:i:s',$time);                   //generating date
$f = fopen("log.php", "a");                          //opening files
$counter = fgetc("hitleap.txt");
$f2 = fopen("hitleap.txt", "w+");

if($referer == "http://hitleap.com/traffic-exchange"){
fwrite($f2, $counter++);                             
fclose($f2);
} else { 
fwrite ($f, '<div class="spoiler"><input type="button" onclick="showSpoiler(this)" value="Show/Hide" />
Data/Ora: <b>['.$date.']</b><br>
<div class="inner" style="display:none">
IP: <b>['.$ip.']</b> <br>
Provenienza: <b>['.$referer.']</b>
</div></div><br>



 ');
fclose($f);
}

基本上,如果站点访问者来自hitleap站点,我想在txt文件中增加一个数字1.如果不是,请将其IP和引用程序添加到另一个日志文件中。 第二部分工作得很好,但我仍然不能让第一部分工作

每当“else”应用时,hitleap.txt也会以某种方式刷新。

修改 解决方式如下:

$ip = $_SERVER['REMOTE_ADDR'];
$referer = $_SERVER['HTTP_REFERER'];
$time = time();
$date = date('d-m-y H:i:s',$time);
$hits = file_get_contents("hitleap.txt");
$nhits = $hits+1;

if($referer == "http://XXX"){
$f2 = fopen("hitleap.txt", "w+");
fwrite($f2, $nhits);
fclose($f2);
} else {
$f = fopen("log.php", "a");
fwrite ($f, 'wh@tever u want here');
fclose($f);
}

似乎对我很好

2 个答案:

答案 0 :(得分:2)

你想用

fwrite($f2, ++$counter);

而不是

fwrite($f2, $counter++); 

正在发生的事情是,在将变量写入文件后而不是之前将变量递增。解决方案将在写入之前递增变量。

答案 1 :(得分:1)

您的最终代码是:

$ip = $_SERVER['REMOTE_ADDR'];                       //get IP
$referer = $_SERVER['HTTP_REFERER'];                 //get referer
$time = time();                                      //extracting timestamp
$date = date('d-m-y H:i:s',$time);                   //generating date
$f = fopen("log.php", "a");                          //opening files
$counter = fgetc("hitleap.txt");

// this line has been moved into the if block

if($referer == "http://hitleap.com/traffic-exchange"){
$f2 = fopen("hitleap.txt", "w+"); // here it is
fwrite($f2, ++$counter);                       // using ++$counter      
fclose($f2);
} else { 
fwrite ($f, '<div class="spoiler"><input type="button" onclick="showSpoiler(this)" value="Show/Hide" />
Data/Ora: <b>['.$date.']</b><br>
<div class="inner" style="display:none">
IP: <b>['.$ip.']</b> <br>
Provenienza: <b>['.$referer.']</b>
</div></div><br>



 ');
fclose($f);
}