2016-08-11 7 views
0

私は新しいボストンの "Beginner php tutorials"と呼ばれるYouTubeチュートリアルをPHPでコーディングすることを学んでいます。私はPHPを使用してユニークなヒットカウンターを作成しようとしていたが、何らかの理由で私のコードが動作しません。あなたが私を助けてくれることを願っています。PHPでユニークなヒットカウンタファイルを作成しようとしたときにエラーが発生しました

は、ここに私のコードです:あなたはのfuctionを書いた

<?php 

function hit_counter() { 
    $ip_address=$_SERVER['REMOTE_ADDR']; 
    echo $ip_address; 
    $ip_file=file('ip.txt'); 

    foreach ($ip_file as $ip) { 
     $ip_single= trim($ip); 
     if (@$ip_address!=$ip_single) { 
      $ip_value=false; 
      break; 
     } else { 
      $ip_value=true;  
     } 
    } 

    if (@ip_value==false) { 
     $filename='count.txt'; 
     $handle=fopen($filename, 'r'); 
     $current=fread($handle, filesize($filename)); 
     fclose($handle); 

     $count=$current+1; 

     $handle=fopen($filename, 'w'); 
     fwrite($filename, $count); 
     fclose($handle); 

     $handle=fopen('ip.txt', 'a'); 
     fwrite($ip_file, @$ip_address.'\n'); 
     fclose($handle); 
    } 
} 

?> 
+0

簡素化することができたように見えないのですか?エラーまたは例外がスローされていますか?それともコードがあなたが意図したことをしないのですか? –

答えて

0

これは、テストしたが、機能が意味する動作しませんどういうやや

function hit_counter() { 
    /* sourcefile containing ips of visitors */ 
    $file=__DIR__ . '/ip.txt'; 

    /* get the user's ip address */ 
    $ip=trim($_SERVER['REMOTE_ADDR']); 

    /* read contents of sourcefile into an array */ 
    $ips=file($file); 

    /* remove blank spaces from string */ 
    array_walk($ips, function(&$v, $k){ $v=trim($v); }); 

    /* establish baseline count of unique ips */ 
    $count=count($ips); 

    /* Add new entry to file if not found & increment count */ 
    if(!in_array($ip, $ips)){ 
     file_put_contents($file, $ip . PHP_EOL, FILE_APPEND); 
     $count++; 
    } 

    /* return the count for further processing */ 
    return $count; 
} 


$hits=hit_counter(); 
echo "Hits:{$hits}"; 
+0

遅れて申し訳ありませんが、私はコードをチェックし、あなたが書いた新しいコマンドを含むでしょう:))、ありがとう! – INME

0

、それが呼び出されていません。

function doSomething(){ 
    ... execute code here ... 
} 

// Invoke function 
doSomething(); 
関連する問題