您好,欢迎访问一九零五行业门户网

手把手教你用php实现图片上传功能

一 为了测试图片上传功能, 把图片路径保存到数据库, 我们得先新建个测试表 test_img.
create table test_img ( id int(4) unsigned not null auto_increment, path varchar(100) default null, upload_time timestamp default current_timestamp, primary key(id))engine=myisam default charset=utf8
sql 命令: 插入表中时生成一个唯一的数字, 比如测试数据多了, id 是不停地自增, 如果要把 id 回归到 1, 可以尝试以下命令.
alter table test_img auto_increment = 1
二 新建 img.html 文件用于选择上传图片
<!doctype html><html lang="utf-8"><head> <meta charset="utf-8"> <title>图片上传</title></head><body><form action="img.php" method="post" enctype="multipart/form-data"> 选择上传的图片: <input type="file" name="file" accept="image/*"> <br><br> <input type="submit" value="上传"></form>
<form> 标签中的 enctype 控制着是否编码发送表单数据, 默认是 application/x-www-form-urlencoded, 即在发送前编码所有字符.
值描述
application/x-www-form-urlencoded 在发送前编码所有字符 ( 默认)
multipart/form-data 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值
text/plain 空格转换为 “+” 加号,但不对特殊字符编码
<input>标签中的 accept限制上传格式.
三 新建 img.php 用于接受处理图片
$_files 获取图片文件, 将具体文件名字添加到数据表test_img中, move_uploaded_file 将图片文件存储到目标文件夹下, iconv 作字符编码处理, 防止有中文命名的图片上传后出现乱码的情况.
<?phpheader("content-type: text/html;charset=utf-8");$conn = new mysqli('localhost', 'root', '', 'test');if (!$conn) { die("connection failed: " . mysqli_connect_error());}$destination = '../upload/image/';$file = $_files['file']; // 获取上传的图片$filename = $file['name'];$insert = "insert into test_img (path) values ('$filename')";$test = move_uploaded_file($file['tmp_name'], $destination . iconv("utf-8", "gb2312", $filename));if ($insert && $test) { $conn->query($insert);} else { echo '上传失败' . '<br>';}$select = 'select path from test_img';$result = $conn->query($select);while ($row = $result->fetch_assoc()) { echo "<img src=" . $destination . $row['path'] . ">";}
print_r( $_files[‘file’]); // 输出接受到的上传图片得到如下信息
上传图片成功后, 通过数据表图片信息匹配 upload/image 下的图片循环显示出来, 效果如下.
四 写到最后
以上只是分享个 php 粗糙版上传图片的功能实现, 有些细节你大可自己尝试修改完善, 要想学好必须通过亲自动手领悟, 云学习只能撸个皮毛而已, 如果我的分享能让你有点启发的话,不如点个赞激励一下我, 当然不给也行, 我也会自我驱动学习的啦~
感谢大家的阅读,希望大家有所收获
推荐教程:《php教程》
以上就是手把手教你用php实现图片上传功能的详细内容。
其它类似信息

推荐信息