如果文本文件中存在特定文本

时间:2017-07-16 17:46:24

标签: php

我想跟踪哪些网站正在使用我的主题。我在我的主题中添加了一个代码<img src="http://example.com/callback.php">,我的callback.php文件内容是

<?php
    if(!$_SERVER['HTTP_REFERER']){
        echo "No direct access!";
    } else {
        $logfile= 'log.txt';
        if(is_writable($logfile)) {
            $referer = parse_url($_SERVER['HTTP_REFERER']);
            $referer = $referer['host'];
            $fp = fopen($logfile, "a");
            fwrite($fp, $referer);
            fwrite($fp, "\n");
            fclose($fp); 
        } else {
            echo "log.txt is not writable";
        }
    }
?>

但它会在每个页面加载时写入相同的域。我想首先检查域名,如果域名在文本文件中,则不应添加域名。

2 个答案:

答案 0 :(得分:1)

试试这个:

<?php

if (!$_SERVER['HTTP_REFERER']) {
    echo "No direct access!";

    exit();
} 

$logfile= 'log.txt';

if (!is_writable($logfile)) {
    echo "log.txt is not writable";

    exit();
} 

$referer = parse_url($_SERVER['HTTP_REFERER']);
$host = $referer['host'];

$hosts = file($logfile, FILE_IGNORE_NEW_LINES);

if (in_array($host, $hosts)) {
    exit();
}

$handle = fopen($logfile, "a");

fwrite($handle, $host);
fwrite($handle, "\n");

fclose($handle);

供参考,见:

答案 1 :(得分:1)

试试这段代码:

<?php
    if(!$_SERVER['HTTP_REFERER']){
        echo "No direct access!";
        exit();
    } else {
        $logfile= 'log.txt';
        if(is_writable($logfile)) {
            $referer = parse_url($_SERVER['HTTP_REFERER']);
            $referer = $referer['host'];
            $fp = fopen($logfile, "a+");
            $flag=false;
            while(!feof($fp)){
                if(trim(fgets($fp)) === trim($referer))
                $flag=true;
            }
            if(!$flag){
                fwrite($fp, $referer);
                fwrite($fp, "\r\n");
            }
            fclose($fp);
        } else {
            echo "log.txt is not writable";
            exit();
        }
    }
?>