php之上传图片及传数据到mysql

index.html

<form action="php.php" method="post" enctype="multipart/form-data">
        <input type="file" name="filename"/>
        <input type="submit" value="上传文件"/>
</form>

php.php

<?php

try {
    $file = $_FILES['filename'];
    if (!$file['error'] == 0) {
        throw new Exception('上传文件出错');
    }
//文件来源安全性(文件上传白名单)
    if (!$file['tmp_name']) {
        throw new Exception('您的图片来源不安全');
    }
//文件目录
    $dir = 'upload/' . date('ym/');
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    //文件上传大小
    if ($file['size'] > 80000000) {
        throw new Exception('文件不得超过80000000M');
    }
//文件名
    $name = $file['name'];
    $ext = substr($name, strrpos($name, '.'));
    if (!preg_match('/(.jpg)|(.png)|(.gif)$/', $ext)) {
        throw new Exception('图片格式错误');
    }
    $newname = md5(time() . rand(0, 999999999) . rand(111, 9999)) . $ext;
    $filenamea = $file['tmp_name'];
    move_uploaded_file($filenamea, $dir . $newname);
//    数据库连接
    $link = new mysqli('localhost', 'root', 'password', 'image');
    if ($link->connect_errno) {
        unlink($dir . $newname);
        throw new Exception('数据库连接失败');
    }
    $sql = 'INSERT INTO images (`name`,url,`time`) VALUES ("' . $name . '","' . $dir . $newname . '",' . time() . ')';
    var_dump($sql);
    $res = $link->query($sql);
    if (!res) {
        echo '失败';
    }
} catch (Exception $ex) {
    echo $ex->getMessage();
}

 

转载于:https://www.cnblogs.com/wdxue/p/8340198.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值