使用PHP实现文件的上传和检测
使用PHP实现文件的上传和检测
使用PHP的POST进行上传
<?php date_default_timezone_set("PRC");?>
<?php
if(!isset($_POST['submit'])){
echo '
<p>请选择要上传的文件</p>
<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="upfile"/><br/><br/>
<input type="submit" name="submit" value="上传"/>
</form>
';
}else{
$upload_dir=getcwd()."\\img\\"; //getcwd()获取当前脚本目录
if(!is_dir($upload_dir)) //如果目录不存在,则创建
mkdir($upload_dir);
//截取文件后缀
$file = $_FILES['upfile']['name'];
$arr = explode('.', $file);
$extension = end($arr);
function makefilename(){ //根据md5生成上传文件名
$md5file = $_FILES['upfile']['tmp_name'];
$md5 = md5_file($md5file);
$filenames = $_FILES['upfile']['name'];
$extension2 = pathinfo($filenames,PATHINFO_EXTENSION);
$filename = $md5.".".$extension2;
return $filename;
}
//允许的文件后缀
$photo = $extension;
//可添加允许的文件后缀
if(($photo == "jpg") || ($photo == "png") || ($photo == "jpeg")){
$newfilname=makefilename();
$newfile=$upload_dir.$newfilname;
if(!file_exists($newfile)){
move_uploaded_file($_FILES['upfile']['tmp_name'],$newfile);
echo "上传的文件信息:<br/>";
echo "上传前文件名:".$_FILES['upfile']['name']."<br/>";
echo "文件类型:".$_FILES['upfile']['type']."<br/>";
//单位转换
$size = filesize("$upload_dir"."$newfilname");
function trans_byte($byte){
$KB = 1024;
$MB = 1024 * $KB;
$GB = 1024 * $MB;
$TB = 1024 * $GB;
if ($byte < $KB) {
return $byte . "B";
} elseif ($byte < $MB) {
return round($byte / $KB, 2) . "KB";
} elseif ($byte < $GB) {
return round($byte / $MB, 2) . "MB";
} elseif ($byte < $TB) {
return round($byte / $GB, 2) . "GB";
}else {
return round($byte / $TB, 2) . "TB";
}
}
echo "文件大小:".trans_byte($size)."<br/>";
echo "上传后文件名:".$newfilname."<br/>"; //显示路径输出$newfile
echo "文件上传成功"."<br/>";
echo '<a href="JavaScript:history.back()">继续上传</a>';
}else{
$codeerr = $_FILES['upfile']['error'];
if($codeerr == 1){
echo $codeerr."上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。";
}elseif($codeerr == 2){
echo $codeerr."上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。";
}elseif($codeerr == 3){
echo $codeerr."文件只有部分被上传。";
}elseif($codeerr == 4){
echo $codeerr."没有文件被上传。";
}elseif($codeerr == 6){
echo "$codeerr.找不到临时文件夹。";
}elseif($codeerr == 7){
echo $codeerr."文件写入失败。";
}elseif($codeerr == 0){
echo $codeerr."文件已上传并存在";
}else{
echo "其他错误,错误类型:".$codeerr;
}
}
}else{
echo "非法的文件格式";
}
}