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\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);
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值