php实现文件上传

这段内容涉及一个HTML页面和PHP脚本实现的简单文件上传功能。HTML表单允许用户选择文件,然后通过POST方法提交到upload.php。在PHP中,定义了一个UploadFile类,该类包含了检查文件类型、大小、路径的一系列方法,并尝试将上传的文件移动到指定目录。如果文件类型不在允许的列表中,文件过大或目标路径不存在,系统会显示错误消息。否则,文件上传成功。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件上传

1.upload.html


<html>
 <head>
  <meta charset="UTF-8">
  <title>文件上传</title>
 </head>
<form action='upload.php' method='post' enctype='multipart/form-data'>
请选择文件:<input type='file' name='myfile'>
<input type='submit' name='sub'>
</form>
</html>

2.upload.php

<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
</html>
<?php
	class UploadFile{
		private $arr = array('png', 'jpg', 'gif');
		private $size = 100000;
		private $path = './upload/';
		
		private $fileName;
		private $newFileName;
		private $ftype;
		private $fsize;
		private $tempName;
		
		function __construct($file){
			$this -> fileName = $file['myfile']['name'];
			$this -> fsize = $file['myfile']['size'];
			$this -> tempName = $file['myfile']['tmp_name'];
			$this -> getFileType();
			$this -> getNewFileName();
		}
		
		private function getFileType(){
			@$fh = array_pop(explode('.', $this->fileName));
			$this -> ftype = $fh;
		}
		
		private function getNewFileName(){
			$newFileName = time() . rand(100,999) . '.' . $this->ftype;
			$this -> newFileName = $newFileName;
		}
		
		#判断后缀 checkFile()
		
		private function checkFile(){
			//$ft = array_pop(explode('.', $_FILES['myfile']['name']));
			if(!in_array($this->ftype,$this->arr)){
				die('文件类型错误,上传失败');
			
			}
		}
		
		#判断路径 checkPath()
		
		private function checkPath(){
			if(!file_exists($this->path)){
				mkdir($this->path);
			}
			
			
		}
		#判断大小 checkSize()
		
		private function checkSize(){
			if($this->fsize>$this->size){
				die('文件过大,上传失败');
			}
		}
		#共有方法 upload();
		function upload(){
			$this->checkFile();
			$this->checkPath();
			$this->checkSize();
			
			if(!@move_uploaded_file($this->tempName, $this->path . $this->newFileName)){
				die('文件上传失败');
			}echo '文件上传成功';
		
	}
	
	}
	
	
	
	
	$f=new UploadFile($_FILES);
	$f->upload();

运行html代码
在这里插入图片描述
随便上传一个文件
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值