使用PHP进行文件上传,主要使用到表单功能和PHP内置的$_FILES函数功能。接下来我们看如何实现PHP上传功能。例子效果图,此例子是在Mac下进行调试成功的。
PHP上传图片文件的功能代码如下:
<html> <head> <meta charset="utf-8"> <title>Upload File Example</title> <style> body{ width:500px; margin:20px auto; line-height:25px; } img{ display:block; max-width:500px; } h1{ text-align:center; } #uploadfile{ background-color:#eee; text-align:center; width:500px; margin:0 auto; } form{ margin:0px; padding:0px; } #uploadfile .input1{ display:block; width:500px; text-align:center; margin:0 auto; } #uploadfile .input2,.input3{ width:100px; margin:5px 20px; } </style> </head> <body> <h1>Upload File</h1> <div id="uploadfile"> <form enctype="multipart/form-data" action="<?php echo $_SERVER[‘PHP_SELF‘];?>" method="post"> <input class="input1" name="upfile" type="file"> <input class="input2" type="submit" value="确认提交"> <input class="input3" type="reset" value="重置"> </form> </div> <?php if($_FILES["upfile"]["name"]==NULL){ echo "No file choice!"; }else{ $filepath="/Library/WebServer/Documents/"; $tmp_name=$_FILES["upfile"]["tmp_name"]; $filename=$filepath.$_FILES["upfile"]["name"]; echo "<br>"."\$_FILES[‘upfile‘][‘name‘]:".$_FILES["upfile"]["name"]; echo "<br>"."\$_FILES[‘upfile‘][‘size‘]:".GetSize($_FILES["upfile"]["size"]); echo "<br>"."\$_FILES[‘upfile‘][‘type‘]:".$_FILES["upfile"]["type"]; echo "<br>"."\$_FILES[‘upfile‘][‘tmp_name‘]:".$_FILES["upfile"]["tmp_name"]; if(move_uploaded_file($tmp_name,$filename)){ echo "<br>"."已上传至目录:".$filename; if(in_array($_FILES["upfile"]["type"],array("image/png","image/jpg","image/bmp"))){ echo "<br>"."<img src=‘/".$_FILES["upfile"]["name"]."‘ />"; }else{ } }else{ echo "<br>"."Upload faild!"; } } // 将文件大小转成相应计量单位 function GetSize($tmp){ $arr = array("B","KB","MB","GB","TB","PB"); $pos = 0; if(!is_integer($tmp)) return -1; while($tmp>1024 and count($arr)>$pos){ $tmp = $tmp / 1024.0; $pos++; } $tmp = sprintf("%.2f",$tmp); return $tmp.$arr[$pos]; } ?> </body> </html>
使用表单的action可以选点表单提交对象,象本文中的例子是将表单提交给自己进行处理。
method可以选择post或get文件进行提交。
时间: 2024-11-03 21:05:50