Access request details when using Cloudflare workers

Preface: Cloudflare Worker does not have the function of ip and visit logs. So add it manually with another PHP server.




1. Using PHP to write logs


    <?php
    if (isset($_GET["ip"])&&isset($_GET["region"])&&isset($_GET["path"])){
    $ip=$_GET["ip"];
    $region=$_GET["region"];
    $path=$_GET["path"];
    $time=date('Y-m-d H:i:s');
    $filename="log/".date('Ymd').".txt";
    echo $time." IP:".$ip." Region:".$region." Path:".$path;
    $fp=fopen($filename,'a');
    fwrite($fp,$time." IP:".$ip." Region:".$region." Path:".$path."\r\n");
    fclose($fp)
    }
    else{
    echo "Error";
    }
    ?>

2. Add To Workers Dash: 


    const region = request.headers.get('cf-ipcountry').toUpperCase();
    const ip_address = request.headers.get('cf-connecting-ip');
    let { pathname } = new URL(request.url);
    fetch("https://exmaple.com/examplelocation?ip="+ip_address+"&region="+region+"&path="+pathname);

3. Additional: read.php


    <?php
    $filename="log/".date('Ymd').".txt";
    if ( file_exists ( $filename )){
    $fp=fopen($filename,'r');
    $str = fread ( $fp , filesize ( $filename ));
    echo $str = str_replace ( "\r\n" , "<br />" , $str );
    fclose($fp);
    }
    else{
    echo "No Log Today.";
    }
    ?>

4. All function in one file

    <?php
    if (isset($_GET["ip"])&&isset($_GET["region"])&&isset($_GET["path"])){
    $ip=$_GET["ip"];
    $region=$_GET["region"];
    $path=$_GET["path"];
    $time=date('Y-m-d H:i:s');
    $filename="log/".date('Ymd').".txt";
    echo $time." IP:".$ip." Region:".$region." Path:".$path;
    $fp=fopen($filename,'a');
    fwrite($fp,$time." IP:".$ip." Region:".$region." Path:".$path."\r\n");
    fclose($fp);
    }
    elseif(isset($_GET["read"]))
    {
$filename="log/".date('Ymd').".txt";
    if ( file_exists ( $filename )){
    $fp=fopen($filename,'r');
    $str = fread ( $fp , filesize ( $filename ));
    echo $str = str_replace ( "\r\n" , "<br />" , $str );
    fclose($fp);
    }
    else{
    echo "No Log Today.";
    }
    }
    else{
    echo "Error";
    }
    ?>

The End

Comments

Popular posts from this blog

海外回国代理分流

openwrt设置定时任务-远程唤醒计算机

从Blogger转移