本文介绍了在PHP中上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 使用一些优秀的在线教程,我将下面的代码放在一起,允许用户上传图片文件到一个服务器文件夹和文件名和其他细节到一个mySQL数据库。 PHP脚本 <?php //为上传图片定义最大尺寸 // define(MAX_SIZE,100); //定义缩略图的宽度和高度 //注意这两个dimmensions被认为是最大的dimmension,并且不是固定的, //因为我们必须保持图像比例不变,或者它会变形 define(WIDTH,150); define(HEIGHT,100); //这是从上传的图像中创建缩略图图像的函数 //调整尺寸将考虑所定义的宽度和高度,但不会使图像变形函数make_thumb($ img_name,$ filename,$ new_w,$ new_h) { //获取图片扩展名。 $ ext = getExtension($ img_name); //使用gd库中的相应函数创建新图像 if(!strcmp(jpg,$ ext)||!strcmp(jpeg,$ ext)) $ src_img = imagecreatefromjpeg($ img_name); if(!strcmp(png,$ ext)) $ src_img = imagecreatefrompng($ img_name); //获取图像的颜色 $ old_x = imageSX($ src_img); $ old_y = imageSY($ src_img); //接下来我们将计算缩略图图像的新内容 //接下来的步骤将会被采用: // 1.通过将旧的dimmensions与新的 // 2.如果宽度的比例较高,宽度将保持在WIDTH变量 //中的一个定义,并且将计算高度以使图像比率不会改变 // 3.否则,我们将使用图像 //的高度比例作为结果,只有其中一个dimmensions将来自固定元素 $ ratio1 = $ old_x / $ new_w; $ ratio2 = $ old_y / $ new_h; if($ ratio1> $ ratio2){ $ thumb_w = $ new_w; $ thumb_h = $ old_y / $ ratio1; } else { $ thumb_h = $ new_h; $ thumb_w = $ old_x / $ ratio2; } //我们用新的dimmensions创建一个新的图像 $ dst_img = ImageCreateTrueColor($ thumb_w,$ thumb_h); //将大图像调整为新创建的图像 imagecopyresampled($ dst_img,$ src_img,0,0,0,0,$ thumb_w,$ thumb_h,$ old_x,$ old_y ); //将创建的图像输出到文件中。现在我们将把缩略图放到由$ filename 命名的文件中,如果(!strcmp(png,$ ext)) imagepng($ dst_img,$ filename); else imagejpeg($ dst_img,$ filename); //破坏源图像和目标图像。 imagedestroy($ dst_img); imagedestroy($ src_img); } //这个函数读取文件的扩展名。 //通过检查扩展名来确定文件是否为图像。 函数getExtension($ str){ $ i = strrpos($ str,。); if(!$ i){return; } $ l = strlen($ str) - $ i; $ ext = substr($ str,$ i + 1,$ l); return $ ext; } $ title =($ _POST ['title']); if($ title =='')//如果没有设置title $ title ='(No Title Provided)'; //使用(空标题)string //读取用户提交上传文件的名称 $ image = $ _ FILES ['image'] ['name']; if($ image) { //从客户端机器获取文件的原始名称 $ filename = stripslashes($ _ FILES ['image' ]['名称']); //以小写格式获取文件的扩展名 $ extension = getExtension($ filename); $ extension = strtolower($ extension); //如果它不是一个已知的扩展名,我们将假定它是一个错误,打印一个错误信息 //并且不会上传文件,否则我们继续 if( ($ extension!=jpeg)&&($ extension!=png)) { echo'< b>错误! < / B个 - 您试图上传的图片格式不正确。文件格式< b>必须< / b>为以下之一:< b> jpg,jpeg< / b>或< b> png< / b> ;.请再试一次。'; $ errors = 1; } else { //以字节为单位获取图片的大小 // $ _FILES [\'image \'] [\' tmp_name\']是上传文件存储在服务器上的文件的临时文件名 $ size = getimagesize($ _ FILES ['image'] ['tmp_name']); $ sizekb = filesize($ _ FILES ['image'] ['tmp_name']); //将尺寸与我们定义的最大尺寸进行比较,如果更大,则打印错误 if($ sizekb> 1150000) { echo'< b> ;错误! < / B个 - 您尝试上传的文件大于规定的< b> 1MB< / b>限制。请再试一次。'; $ errors = 1; } //我们将给出一个唯一的名字,例如以unix时间格式的时间 $ image_name = time()。'。'。$ title。'。 。 $扩展; //新名称将包含将被存储的完整路径(图像文件夹) $ newname =images /\".$ image_name; $ copied = copy($ _ FILES ['image'] ['tmp_name'],$ newname); if(!$ copied) { // echo'< b>错误! < / B个你的文件没有被加载'; // $ errors = 1; } else { //新的缩略图将被放置在images / thumbs /文件夹中 $ thumb_name ='images / thumbs /'.$ image_name ; //调用将创建缩略图的函数。该函数将获得参数 //图像名称,缩略图名称以及缩略图所需的宽度和高度 $ thumb = make_thumb($ newname,$ thumb_name,WIDTH,HEIGHT); }}} //如果没有注册错误,打印成功消息并显示创建的的缩略图,如果(isset($ _ POST ['Submit'])& &!$ errors) { // echo'< br>< b>成功! < / B个 - 您的图片已上传< / br>'; // echo'< img src ='。$ thumb_name。'>'; } require(mapmyfindsdbinfo.php); //从表单获取数据 $ userid = $ _POST [userid]; $ locationid = $ _POST [locationid]; $ findosgb36lat = $ _POST [findosgb36lat]; $ findosgb36lon = $ _POST [findosgb36lon]; $ dateoftrip = $ _POST [dateoftrip]; $ findcategory = $ _POST [findcategory]; $ findname = $ _POST [findname]; $ finddescription = $ _POST [finddescription]; $ detectorid = $ _POST [detectorname]; $ searchheadid = $ _POST [searchheadname]; if(empty($ _ POST [detectorsettings])){ $ettersettings ='没有提供详细信息。 }其他{ $ detectorsettings = $ _POST [检测器设置]; } if(empty($ _ POST [pasref])){ $ pasref ='No PAS Ref。提供的号码。 } else { $ pasref = $ _POST [pasref]; } if(empty($ _ POST [additionalcomments])){ $ additionalcomments ='没有额外的评论。 } else { $ additionalcomments = $ _POST [additionalcomments]; } $ makepublic = $ _POST [makepublic]; 打开到MySQL服务器的连接 $ conn = mysql_connect(hostname,$ username,$ password); if(!$ conn){ die('Not connected:'。mysql_error()); //设置活动的MySQL数据库 $ db_selected = mysql_select_db($ database,$ conn); if(!$ db_selected){ die('can not use db:'。mysql_error()); $ sql =INSERT INTO查找值(用户标识符,位置标识符,查找符号,查找符号,查找描述符('$ userid','$ locationid','$ findosgb36lat','$ findosgb36lon','$ dateoftrip','$ findcategory','$ findname','$ finddescription','$ detectorid','$ searchheadid' ,'$ detectorsettings','$ pasref','$ additionalcomments','$ makepublic'); $ result = mysql_query($ sql,$ conn); $ findid = mysql_insert_id($ conn); $ sql =INSERT INTO testimages(title,imagename,findid)VALUES('$ title','$ image_name','$ findid'); $ result = mysql_query($ sql,$ conn); $ b $ if(!$ result){ die('Invalid query:'。mysql_error()); } ?> HTML表单 < form name =savemyfindstolocationmethod =postenctype =multipart / form-dataaction =savemyfindstolocation.php> < p align =left>是否要添加查找图片< label>< / label> < label>< / label> < / p> < div align =left> < table id =addfiletableborder =1style =table-layout:auto> < tr> < td>& nbsp;< / td> < td>< div align =center>标题< / div>< / td> < td>< div align =center>档案位置< / div>< / td> < / tr> < tr> < td width =20>< input name =selecttype =radioid =selecttitle =/>< / td> < td width =144>< input name =titletype =textid =title/>< / td> < td width =314>< input name =imagetype =fileid =imageonchange =addRow();大小= 40/>< / TD> < / tr> < / table> < div align =justify> < input type =submitname =deleterowvalue =Delete Row/> < / div> < / div> < input name =submittype =submitvalue =Submit/> < / form> 这一切都很好,但我现在想扩展允许用户上传的功能一次超过1个文件。我已经做了一些研究,看看如何上传多个文件,但是我对PHP相当陌生,并且有些不确定哪种方法是最好的方式。 我只是想知道是否有人可以看看我已经放在一起,并提供一些指导,我可以如何改变这个上传表单提交多个文件。 非常感谢 解决方案 foreach($ _ FILES ['image'] ['name'] as $ i => $ name) { //现在$ name包含原始文件名 $ tmp_name = $ _FILES ['image'] ['tmp_name'] [$ i]; $ error = $ _FILES ['image'] ['error'] [$ i]; $ size = $ _FILES ['image'] ['size'] [$ i]; $ type = $ _FILES ['image'] ['type'] [$ i]; if($ error === UPLOAD_ERR_OK) { $ extension = getExtension($ name); if(!in_array(strtolower($ extension,array('jpg','jpeg','png')) { //错误,检测到无效扩展} else if($ size> $ maxAllowedFileSize / *需要在别处定义* /) { //错误,文件太大} else { //没有错误 $ newFileName ='foo'; //你可能会想为每个文件指定一些独特的东西 if(move_uploaded_file($ tmp_file,$ newFileName) ) { //上传的文件已成功移至新位置 $ thumbName ='thumb_image_name'; $ thumb = make_thumb($ newFileName,$ thumbName,WIDTH,HEIGHT); $ b code HTML < form method =postenctype =multipart / form-data> < input name =image []type =fileclass =image-upload/> < input name =image []type =fileclass =image-upload/> < input name =image []type =fileclass =image-upload/> < input name =image []type =fileclass =image-upload/> < input name =image []type =fileclass =image-upload/> < / form> 请注意输入元素的名称。最后的 [] 会导致PHP创建一个数组,并将这些项添加到数组中。 I wonder whether someone may be able to help me please.Using some excellent online tutorials I've put together the code below which allows a user to upload image files to a server folder and the filename and other details to a mySQL database.PHP Script<?php//define a maxim size for the uploaded images//define ("MAX_SIZE","100");// define the width and height for the thumbnail// note that theese dimmensions are considered the maximum dimmension and are not fixed,// because we have to keep the image ratio intact or it will be deformeddefine ("WIDTH","150");define ("HEIGHT","100");// this is the function that will create the thumbnail image from the uploaded image// the resize will be done considering the width and height defined, but without deforming the imagefunction make_thumb($img_name,$filename,$new_w,$new_h){//get image extension.$ext=getExtension($img_name);//creates the new image using the appropriate function from gd libraryif(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))$src_img=imagecreatefromjpeg($img_name);if(!strcmp("png",$ext))$src_img=imagecreatefrompng($img_name);//gets the dimmensions of the image$old_x=imageSX($src_img);$old_y=imageSY($src_img);// next we will calculate the new dimmensions for the thumbnail image// the next steps will be taken:// 1. calculate the ratio by dividing the old dimmensions with the new ones// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable// and the height will be calculated so the image ratio will not change// 3. otherwise we will use the height ratio for the image// as a result, only one of the dimmensions will be from the fixed ones$ratio1=$old_x/$new_w;$ratio2=$old_y/$new_h;if($ratio1>$ratio2) {$thumb_w=$new_w;$thumb_h=$old_y/$ratio1;}else {$thumb_h=$new_h;$thumb_w=$old_x/$ratio2;}// we create a new image with the new dimmensions$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);// resize the big image to the new created oneimagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);// output the created image to the file. Now we will have the thumbnail into the file named by $filenameif(!strcmp("png",$ext))imagepng($dst_img,$filename);elseimagejpeg($dst_img,$filename);//destroys source and destination images.imagedestroy($dst_img);imagedestroy($src_img);}// This function reads the extension of the file.// It is used to determine if the file is an image by checking the extension.function getExtension($str) {$i = strrpos($str,".");if (!$i) { return ""; }$l = strlen($str) - $i;$ext = substr($str,$i+1,$l);return $ext;}$title = ($_POST['title']);if ($title == '') // if title is not set$title = '(No Title Provided)';// use (empty title) string//reads the name of the file the user submitted for uploading$image=$_FILES['image']['name'];if ($image){// get the original name of the file from the clients machine$filename = stripslashes($_FILES['image']['name']);// get the extension of the file in a lower case format$extension = getExtension($filename);$extension = strtolower($extension);// if it is not a known extension, we will suppose it is an error, print an error message//and will not upload the file, otherwise we continueif (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")){echo '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "jpg", "jpeg" </b> or <b> "png" </b>. Please try again.';$errors=1;}else{// get the size of the image in bytes// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server$size=getimagesize($_FILES['image']['tmp_name']);$sizekb=filesize($_FILES['image']['tmp_name']);//compare the size with the maxim size we defined and print error if biggerif ($sizekb > 1150000){echo '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';$errors=1;}//we will give an unique name, for example the time in unix time format$image_name=time().'.'.$title.'.'.$extension;//the new name will be containing the full path where will be stored (images folder)$newname="images/".$image_name;$copied = copy($_FILES['image']['tmp_name'], $newname);if (!$copied){//echo '<b> Error! </b> Your file has not been loaded';//$errors=1;}else{// the new thumbnail image will be placed in images/thumbs/ folder$thumb_name='images/thumbs/'.$image_name;// call the function that will create the thumbnail. The function will get as parameters//the image name, the thumbnail name and the width and height desired for the thumbnail$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);} }}//If no errors registred, print the success message and show the thumbnail image createdif(isset($_POST['Submit']) && !$errors){//echo '<br><b> Success! </b> - Your image has been uploaded</br>';//echo '<img src="'.$thumb_name.'">';}require("mapmyfindsdbinfo.php");// Gets data from form$userid = $_POST["userid"];$locationid = $_POST["locationid"];$findosgb36lat = $_POST["findosgb36lat"];$findosgb36lon = $_POST["findosgb36lon"];$dateoftrip = $_POST["dateoftrip"];$findcategory = $_POST["findcategory"];$findname = $_POST["findname"];$finddescription = $_POST["finddescription"];$detectorid= $_POST["detectorname"];$searchheadid = $_POST["searchheadname"];if( empty($_POST["detectorsettings"]) ) {$detectorsettings = 'No details provided.'; } else {$detectorsettings = $_POST["detectorsettings"]; }if( empty($_POST["pasref"]) ) {$pasref = 'No PAS Ref. number provided.'; } else {$pasref = $_POST["pasref"]; }if( empty($_POST["additionalcomments"]) ) {$additionalcomments = 'No additional comments made.'; } else {$additionalcomments = $_POST["additionalcomments"]; }$makepublic = $_POST["makepublic"];// Opens a connection to a MySQL server$conn = mysql_connect ("hostname", $username, $password);if (!$conn) { die('Not connected : ' . mysql_error());}// Set the active MySQL database$db_selected = mysql_select_db($database, $conn);if (!$db_selected) { die ('Can\'t use db : ' . mysql_error());}$sql = "INSERT INTO finds (userid, locationid, findosgb36lat, findosgb36lon, dateoftrip, findcategory, findname, finddescription, detectorid, searchheadid, detectorsettings, pasref, additionalcomments, makepublic) VALUES ('$userid', '$locationid', '$findosgb36lat', '$findosgb36lon', '$dateoftrip', '$findcategory', '$findname', '$finddescription', '$detectorid', '$searchheadid', '$detectorsettings', '$pasref', '$additionalcomments', '$makepublic')";$result = mysql_query($sql, $conn);$findid = mysql_insert_id($conn);$sql = "INSERT INTO testimages (title, imagename, findid) VALUES ('$title', '$image_name', '$findid')";$result = mysql_query($sql, $conn);if (!$result) { die('Invalid query: ' . mysql_error());}?>HTML Form<form name="savemyfindstolocation" method="post" enctype="multipart/form-data" action="savemyfindstolocation.php"> <p align="left">Do You Wish To Add Find Images<label></label> <label></label> </p> <div align="left"> <table id="addfiletable" border="1" style="table-layout:auto"> <tr> <td> </td> <td><div align="center">Title</div></td> <td><div align="center">File Location </div></td> </tr> <tr> <td width="20"><input name="select" type="radio" id="select" title=""/></td> <td width="144"><input name="title" type="text" id="title"/></td> <td width="314"><input name="image" type="file" id="image" onchange="addRow();" size="40"/></td> </tr> </table> <div align="justify"> <input type="submit" name="deleterow" value="Delete Row" /> </div> </div> <input name="submit" type="submit" value="Submit" /></form>It all works well, but I'd now like to extend the functionality of allowing a user to upload more than 1 file at a time. I've done a fair bit of research to look at how to upload multiple files, but I'm fairly new to PHP and a little unsure as to which is the best way to progress this.I just wondered whether someone could perhaps have a look at what I've put together and offer some guidance on how I can change this to upload mutiple files upon the form submit.Many thanks 解决方案 PHPforeach($_FILES['image']['name'] as $i => $name){ // now $name holds the original file name $tmp_name = $_FILES['image']['tmp_name'][$i]; $error = $_FILES['image']['error'][$i]; $size = $_FILES['image']['size'][$i]; $type = $_FILES['image']['type'][$i]; if($error === UPLOAD_ERR_OK) { $extension = getExtension($name); if( ! in_array(strtolower($extension, array('jpg', 'jpeg', 'png') ) { // Error, invalid extension detected } else if ($size > $maxAllowedFileSize /* needs to be defined elsewhere */) { // Error, file too large } else { // No errors $newFileName = 'foo'; // You'll probably want something unique for each file. if(move_uploaded_file($tmp_file, $newFileName)) { // Uploaded file successfully moved to new location $thumbName = 'thumb_image_name'; $thumb = make_thumb($newFileName, $thumbName, WIDTH, HEIGHT); } } }}HTML<form method="post" enctype="multipart/form-data"> <input name="image[]" type="file" class="image-upload" /> <input name="image[]" type="file" class="image-upload" /> <input name="image[]" type="file" class="image-upload" /> <input name="image[]" type="file" class="image-upload" /> <input name="image[]" type="file" class="image-upload" /> <!-- You need to add more, including a submit button --></form>Note the name of the input elements. The [] at the end cause PHP to create an array and add the items to the array. 这篇关于在PHP中上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-05 13:46