关于PHP的多图上传和处理,麻烦高手写一段代码供研习
需求如下:
一个产品名下面有4张图片。图片上传到当前路径的“upimg”文件夹中,图片路径要存到mysql对应的字段里。
所以我在做产品资料填入的时候,针对同一个产品名,必须上传4个图片。
---------数据库结构:
数据库名:Atest,
表名:prodcut,
表对应的字段:pname,pic1,pic2,pic3,pic4...(均为char类型)
--------HTML的表单我如此设计:
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><form name="myform" action="upload.php" method="post" enctype="multipart/form-data"> 产品名称: <input type="text" name="pname" /> <br /> 产品图片1:<input type="file" name="pic1"> <br /> 产品图片2:<input type="file" name="pic2"> <br /> 产品图片3:<input type="file" name="pic3"> <br /> 产品图片4:<input type="file" name="pic4"> <p /> <input type="hidden" name="MAX_FILE_SIZE" value="2000000" /> <input type="submit" name="submit" value="提交"> </form>
<?php$uploaddir = "../images/upfiles/";//图片存放文件夹,如果不存在,就创建(得有权限) if(!file_exists($uploaddir)) { mkdir($uploaddir); }$type=array("jpg","gif","bmp","jpeg","png");//限定上传文件的格式$patch="testupload/";//上传类所在的路径---这个可选填function fileext($filename)//取得上传文件的扩展名(上传多个图片时,需要分别对其重命名,否则会报错说函数多次声明违法){return substr(strrchr($filename, '.'), 1);}function random($length)//取得随机数,好像是用哈希算法得到的(上传多个图片时,需要分别对其重命名,否则会报错说函数多次声明违法){$hash = 'CR-';$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';$max = strlen($chars) - 1;mt_srand((double)microtime() * 1000000);for($i = 0; $i < $length; $i ){$hash .= $chars[mt_rand(0, $max)];}return $hash;}$a=strtolower(fileext($_FILES['pic']['name']));//这里的pic就是你HTML表单里的图片域的name="pic"(上传多个图片时,需要分别对其重命名,否则会报错说函数多次声明违法)if(!in_array(strtolower(fileext($_FILES['pic']['name'])),$type))//这里记得对应改函数名和pic的名字{$text=implode(",",$type);echo "You can only upload the following types of files:",$text,"<br /> <a href='upload_pro.php'>return and try again?click me</a>";exit;}else{$filename=explode(".",$_FILES['pic']['name']);//同上,pic需要对应改名do{$filename[0]=random(10); //用到函数random时,一样要对应改名$name=implode(".",$filename);//$name1=$name.".Mcncc";$uploadfile=$uploaddir.$name;//这个$uploadfile就是你要插入数据库相应字段的图片路径,需要相应做变化}while(file_exists($uploadfile));//函数名需要对应最变更if (move_uploaded_file($_FILES['pic']['tmp_name'],$uploadfile))//PIC需要对应最变更{if(is_uploaded_file($_FILES['pic']['tmp_name']))//pic需要对应做变更{echo "the Images Upload failed!";}else{echo "<center>Your file has been uploaded: </center><br><center><img src='$uploadfile' /></center>";//src=后面也要对应最变更echo "<br><center><a href='upload_pro.php'>Continue to upload</a></center>";}}}?><br><font color="#e78608">------解决方案--------------------</font><br>一个测试例
<form name="myform" method="post" enctype="multipart/form-data"> <br> 文件1: <input type="file" name="pic1"> <br /><div class="clear"></div>