2016-06-27 6 views
0

私は単純なスクリプトを持っているだけで、リンクをクリックした回数、PHPスクリプトはリンクのための "counter.txt"ファイルを読むID/URL/Label/Countその後、1をカウントし、 "counter.txt"に書き込んでリダイレクトします。私のPHPスクリプトはいつか空白のデータを書き込む

counter.txt:

Label 1|1|http://google.com|1 
Label 2|2|http://google.us|1 
Label 3|3|http://google.uk|1 

link.php:

<?php 

//gets the content from "counter.txt" 
$filecontent = file_get_contents('counter.txt'); 

//separates the contents of counter.txt by "\n" (spaces) 
$filelines = explode("\n", $filecontent); 

$url_array = null; 

$new_file_content = ""; 

//for each $filelines variable, assign it as $fileline and execute code 
foreach ($filelines AS $fileline) 
{ 
//separates the contents of $fileline by "|" 
    $filelines_exploded = explode("|", $fileline); 

    //assigns counter.txt label to a variable 
    $label  = $filelines_exploded[0]; 
    //assigns counter.txt id's to a variable 
    $click_id = $filelines_exploded[1]; 
    //assigns counter.txt url's to a variable 
    $click_url = $filelines_exploded[2]; 
    //assigns counter.txt click count to a variable 
    $click_count = $filelines_exploded[3]; 

    if ($_REQUEST["id"] == $click_id) 
    { 
     //$url_array contains all of the variables in an array 
     $url_array = $filelines_exploded; 
     //string to rebuild the counter.txt file 
     $new_file_content .= $label . "|" . $click_id . "|" . $click_url . "|" . ((int) $click_count + 1); 
    } 
    else 

    { 
     $new_file_content .= $fileline; 
    } 
    //adds a line break when rebuilding the counter.txt 
    $new_file_content .= "\n"; 
} 
//file_put_contents to rewrite the file 
file_put_contents('counter.txt', trim($new_file_content)); 
//redirects to the link gathered from the counter.txt file 
header("HTTP/1.1 301 Moved Permanently"); 
header('Location: ' . $url_array[2]); 
exit; 
?> 

スクリプト空白になっcounter.txt、いつか働いたが、すべてのデータを失った、私は知りませんなぜ、私のコードに間違っているか見てみてください。

感謝/

+2

dbを使用した場合、これは10億倍になります。 –

+0

まず、file_get_contentsの代わりにfileを使用して、explode( '\ n'、$ var)を作成せずに配列を取得してください。 http://php.net/manual/en/function.file.php – legomolina

答えて

2

これが第一のインスタンスを書き込む前に、それをクリアしただけのように2人の訪問者があなたのファイルを読むために2番目のインスタンスを引き起こし、同時に近くの非常にあなたのリンクをクリックする競合状態の間に発生する可能性があります。この結果、インスタンス2は空のファイルを作成します。

手始めに、あなたはあなただけのファイルの末尾に新しいクリックを追加しているように、あなたますfile_put_contentsでフラグFILE_APPENDを使用して、代わりに完全に書き換えることで、問題のこのやや少ないを作ることができます。

次に、PHPの関数flock()を使って、問題のファイルに対して書き込みロックを試してみることができます。あなたのスクリプトがflock()ファイルのロックを取得してそれに従っているならば、ファイルでターンを得るまで、すべてのスレッドがブロックされて競合状態が発生するのを防ぐことができます。

私の意見では、このような競合状態を心配する必要がある場合は、このシステムをデータベースに移動する準備ができているかもしれません。新しいシステムでは、新しいクリック行の作成について心配する必要はありません(たとえ時々flock()が特定の構成で信頼できないように見える)ほとんどのデータベースエンジンでテーブルをロックするのは非常に簡単です。

+0

ありがとうございます、私はあなたが正しいと思います。データベースを持つ別のソリューションを探しているだけで、他のスクリプトを知っていますか? – Tran

+0

私はすぐにはリンクがありませんが、データベースアプリケーションの作成時に質問がある場合は、質問に私にタグを付けることができます –

関連する問題