php原生上传文件,重复文件自动修改文件名副本为‘文件名(1++)’,需配合数据库

 //这里是点击提交后连接的后端php,前端页面请根据需求自行添加

<?php
//插入连接数据库的相关信息
require_once(dirname(__FILE__).'/../conn.php');//数据库信息
$conn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);//连接数据库
if(! $conn )//判断连接
{
    die('Could not connect: ' . mysqli_error());
}
mysqli_query($conn , "set names utf8");//编译
?>
<?php
$temp = explode(".", $_FILES["file"]["name"]);//文件名和后缀分割   单独取出以数组形式
$type=$_FILES['file']['type'];
$size=$_FILES["file"]["size"]/1024;//文件大小
$name1=($temp[0]);//获取文件名
$src="upload/".$_FILES['file']['name'];
$extension = end($temp);     // 获取文件后缀名
if (!$name1){
    echo '<script>alert("文件名不能为空");history.go(-1)</script>';
}else {
    if ($_FILES["file"]["error"] > 0) {
        echo "错误:" . $_FILES["file"]["error"] . "<br>";
    } else {
        $sql = "SELECT * FROM `upload`where `name`='" . $name1 . "'";
        $result = mysqli_query($conn, $sql);
        $num = mysqli_num_rows($result);

        if ($num > 0) {
            for ($i = 1; mysqli_num_rows($result) > 0; $i++) {
                $name2 = $name1;
                $name3 = $name2 . '(' . $i . ')';
                $result = mysqli_query($conn, "SELECT * FROM `upload` where `name`='" . $name3 . "'");

                if (mysqli_num_rows($result) < 1) {
                    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $name3 . '.' . $extension);//保存文件
                    $query = "insert into `upload`(`name`,`src`)
            values('" . $name3 . "','" . $src . "')";
                    $result = mysqli_query($conn, $query);
                    if (!$result) {
                        echo '<script>alert("上传失败");history.go(-1)</script>';
                    } else {
                        echo '<script>alert("上传成功,文件名为{ ' . $name3 . ' }");location.href="index.html"</script>';

                    }

                }
            }

        }

        move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);//保存文件
        $query = "insert into `upload`(`name`,`src`)
            values('" . $name1 . "','" . $src . "')";
        $result = mysqli_query($conn, $query);
        if (!$result) {
            echo '<script>alert("上传失败");history.go(-1)</script>';
        } else {
            echo '<script>alert("上传成功,文件名为{' . $name1 . '}");location.href="index.html"</script>';

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值