PHP文件操作-读取数据库文件路径复制到另一个目录
PHP文件操作
读取数据库文件路径复制到另一个目录
代码:
<?php
date_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
", FILE_APPEND);
$result = $mysqli->query($value);
if($result == false){
file_put_contents($log, date("Y-m-d H:i:s") . " SQLERROR 查询SQL失败:$value
", 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
", 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
", FILE_APPEND);
}else{
file_put_contents($log, date("Y-m-d H:i:s") . " ERROR 创建目录失败:$root_cp_tmp
", 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
", FILE_APPEND);
}else{
file_put_contents($log, date("Y-m-d H:i:s") . " ERROR 复制失败:" . json_encode($result_info) . " 文件:$img
", FILE_APPEND);
}
}
}
}catch(Exception $e){
file_put_contents($log, date("Y-m-d H:i:s") . " SYSERROR 报错了:" . $e->getMessage() . "
", FILE_APPEND);
}
}声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: PHP处理Linux中生成文件目录及读取内容遍历应用
- 下一篇: PHP-获取目录中的所有文件和子目录
