鍍金池/ 問(wèn)答/PHP/ PHP 怎樣實(shí)現(xiàn)兩個(gè)站點(diǎn)文件同步

PHP 怎樣實(shí)現(xiàn)兩個(gè)站點(diǎn)文件同步

  1. 在一臺(tái)服務(wù)器寫了一個(gè)無(wú)限刷新,檢查文件沒(méi)有被修改過(guò)。
  2. 另一臺(tái)服務(wù)器寫了一個(gè)PHP 傳送文件
  3. 文件傳完就記到log 更新時(shí)間沒(méi)有繼續(xù)傳。

一道練習(xí)題要求 服務(wù)器只允許用PHP代碼實(shí)現(xiàn),我草搞了一下,
最終實(shí)現(xiàn),定時(shí)檢查,A服務(wù)器下的server_folder B 備份服務(wù)器文件數(shù)保持一樣 。
PHP filemtime("test.txt"); 用來(lái)檢查文件最后的修改時(shí)間,有變就要傳到備份站點(diǎn)。

check.php

$filelist = file_get_contents('http://localhost/server_folder');

$file = 'savefile.dat';
file_get_contents($file);

$current = json_encode( array("fileslist"));
file_put_contents($file, $current);

echo "<script>location:reload();</script>";
-------------------------------


POST.php

function send_post($url, $post_data) {  
  
  $postdata = http_build_query($post_data);  
  $options = array(  
    'http' => array(  
      'method' => 'POST',  
      'header' => 'Content-type:application/x-www-form-urlencoded',  
      'content' => $postdata,  
      'timeout' => 15 * 60 
    )  
  );  
  $context = stream_context_create($options);  
  $result = file_get_contents($url, false, $context);  
  
  return $result;  
}  
  
//使用方法  
$post_data = array(  
  'username' => 'stclair2201',  
  'password' => 'handan'  
);  
send_post('http://www.xxxxxcn', $post_data);

function request_by_curl($remote_server, $post_string) {  
  $ch = curl_init();  
  curl_setopt($ch, CURLOPT_URL, $remote_server);  
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' . $post_string);  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
  curl_setopt($ch, CURLOPT_USERAGENT, "waitalone.cn's CURL Example beta");  
  $data = curl_exec($ch);  
  curl_close($ch);  
  
  return $data;  
} 
log.php


function save_log($res) {
    $err_date = date("Ym", time());
    //$address = '/var/log/error';
    $address = './error';
    if (!is_dir($address)) {
        mkdir($address, 0700, true);
    }
    $address = $address.'/'.$err_date . '_error.log';
    $error_date = date("Y-m-d H:i:s", time());
    if(!empty($_SERVER['HTTP_REFERER'])) {
        $file = $_SERVER['HTTP_REFERER'];
    } else {
        $file = $_SERVER['REQUEST_URI'];
    }
    if(is_array($res)) {
        $res_real = "$error_date\t$file\n";
        error_log($res_real, 3, $address);
        $res = var_export($res,true);
        $res = $res."\n";
        error_log($res, 3, $address);
    } else {
        $res_real = "$error_date\t$file\t$res\n";
        error_log($res_real, 3, $address);
    }
}
回答
編輯回答
憶往昔

去github上參考很多

2017年1月7日 04:44
編輯回答
哚蕾咪

服務(wù)器文件同步可以用:rsync

2017年3月4日 18:01