Has optimized PHP click number statistics code


Has optimized PHP click number statistics code

< ?php
error_reporting(E_ALL);

$ROOT_PATH = '../';

include_once($ROOT_PATH . "include/config.php");$update_time = 1800;//The refresh time, second

$article_id = (isset($_GET['article_id']) && is_numeric($_GET['article_id']) && $_GET['article_id'] > 0) ? intval($_GET['article_id']) : 0;
if ($article_id > 0) {
    $filename = $ROOT_PATH . ‘log/click_log.txt’;


    $s = ”;
    if (file_exists($filename)) {
        $content = file_get_contents($filename);
        $d_ary = array();
        if ($content) {
            $ary = explode(”\n”, $content);
            foreach ($ary as $line) {
                $data_ary = explode(’|', $line);
                if (is_numeric($data_ary[0]) && is_numeric($data_ary[1])) {
                    $d_ary[$data_ary[0]] = $data_ary[1];
                }
            }
        }
        if (array_key_exists($article_id, $d_ary)) {
            $d_ary[$article_id] = $d_ary[$article_id]+1;//Increases 1 click
        } else {
            $d_ary[$article_id] = 1;
        }
        foreach ($d_ary as $key => $val) {
            $s .= $key . ‘|’ . $val . “\n”;
        }
    } else {
        $s .= $article_id . ‘|1′ . “\n”;//Initialization record file
    }

    //Writes file
    $fp = fopen($filename, “w”);
   //Locking
if (flock($fp, LOCK_EX)) {
    fwrite($fp, $s);
    flock($fp, LOCK_UN); //release locks
}
    //fwrite($fp, $s);
    fclose($fp);
    @chmod($filename, 0777);

    $last_update = file_get_contents(’../log/last_update.txt’);

    $last_update = intval($last_update);
    if (($last_update + $update_time) < time()) {
        require_once(”adodb.inc.php”);
        $db = NewADOConnection(”$DB_TYPE”);
        $db->debug = true;

        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
        if (!$db->Connect(”$DB_HOST”, “$DB_USER”, “$DB_PASS”, “$DB_DATABASE”)) {
            exit(Error … ‘);
        }

        $content = file_get_contents($filename);
        $d_ary = array();
        if ($content) {
            $ary = explode(”\n”, $content);
            foreach ($ary as $line) {
                $data_ary = explode(’|', $line);
                if (is_numeric($data_ary[0]) && is_numeric($data_ary[1])) {
                    $sql = “UPDATE article SET hits=hits+” . $data_ary[1] . ” WHERE id=” . $data_ary[0];
                    $db->Execute($sql);
                }
            }
        }

         $fp = fopen($filename, “w”);
        fwrite($fp, ”);
        fclose($fp);
        @chmod($filename, 0777);
        $fp = fopen(’../log/last_update.txt’, “w”);
        fwrite($fp, time());
        fclose($fp);
        @chmod(’../log/last_update.txt’, 0777);  

        $db->Close();
    }
    exit();
}

?>

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)