PHP檔案操作
讀取資料庫檔案路徑複製到另一個目錄
代碼:
<?phpdate_default_timezone_set('Asia/Shanghai'); // 設定時區$db_host = '127.0.0.1';$db_name = 'test_qyg_datas';$db_user = 'root';$db_pwd = 'xxx';$mysqli = new mysqli($db_host, $db_user, $db_pwd, $db_name);$mysqli->set_charset("utf8");$sql_array = array('SELECT image FROM buser_goods_list where image <> "" order by bid ','SELECT image FROM supplier_buser_goods_list where image <> "" order by bid ','SELECT image FROM works_sku where image <> "" order by id ','SELECT image FROM supplier_works_sku where image <> "" order by id ');$fs = DIRECTORY_SEPARATOR; // 檔案分隔字元$root = "{$fs}data{$fs}www{$fs}test";$root_cp = "{$fs}data{$fs}www{$fs}img_cp";$log = 'log.log';foreach ($sql_array as $key => $value) {file_put_contents($log, date('Y-m-d H:i:s') . " 查詢SQL:$value\r\n", FILE_APPEND);$result = $mysqli->query($value);if($result == false){file_put_contents($log, date('Y-m-d H:i:s') . " SQLERROR 查詢SQL失敗:$value\r\n", FILE_APPEND);continue;}try{while ($row = $result->fetch_assoc()) {if(empty($row['image'])) continue;$images = explode(',', $row['image']);foreach ($images as $k => $img) {if(stripos($img, 'http') !== false){// 檔案路徑包含http$preg = '/^(http:\/\/?[^\/]+)/i'; // 匹配http網域名稱正則preg_match($preg, $img,$res);$img = str_replace($res[0], '', $img);}if(!file_exists($root . $img)){file_put_contents($log, date('Y-m-d H:i:s') . " ERROR 檔案不存在:$img\r\n", FILE_APPEND);continue;}$img_index = strripos($img, '/') + 1;$folder = substr($img, 0, $img_index);$file = substr($img, $img_index);$root_cp_tmp = $root_cp . $folder;// 判斷檔案夾是否存在if(!file_exists($root_cp_tmp)){$res = mkdir(iconv("UTF-8", "GBK", $root_cp_tmp), 0777, true); // 建立檔案夾if($res == true){file_put_contents($log, date('Y-m-d H:i:s') . " TRUE 建立目錄:$root_cp_tmp\r\n", FILE_APPEND);}else{file_put_contents($log, date('Y-m-d H:i:s') . " ERROR 建立目錄失敗:$root_cp_tmp\r\n", FILE_APPEND);continue;}}// 執行複製檔案命令exec("cp $root$img $root_cp_tmp", $result_info);if(empty($result_info)){file_put_contents($log, date('Y-m-d H:i:s') . " TRUE 複製成功:$img\r\n", FILE_APPEND);}else{file_put_contents($log, date('Y-m-d H:i:s') . " ERROR 複製失敗:" . json_encode($result_info) . " 檔案:$img\r\n", FILE_APPEND);}}}}catch(Exception $e){file_put_contents($log, date('Y-m-d H:i:s') . " SYSERROR 報錯了:" . $e->getMessage() . "\r\n", FILE_APPEND);}}