帮我写一个原生php上传类
时间: 2024-05-05 16:15:25 浏览: 6
以下是一个简单的原生PHP上传类示例:
```php
class Upload {
private $target_dir;
private $target_file;
private $uploadOk = 1;
private $fileType;
public function __construct($target_dir) {
$this->target_dir = $target_dir;
}
public function uploadFile($file) {
$this->target_file = $this->target_dir . basename($file["name"]);
$this->fileType = strtolower(pathinfo($this->target_file,PATHINFO_EXTENSION));
// 检查文件大小
if ($file["size"] > 5000000) {
echo "文件过大!";
$this->uploadOk = 0;
}
// 允许的文件格式
if($this->fileType != "jpg" && $this->fileType != "png" && $this->fileType != "jpeg"
&& $this->fileType != "gif" ) {
echo "只允许上传图片文件!";
$this->uploadOk = 0;
}
// 检查上传状态
if ($this->uploadOk == 0) {
echo "上传失败!";
} else {
if (move_uploaded_file($file["tmp_name"], $this->target_file)) {
echo "文件 ". basename( $file["name"]). " 上传成功!";
} else {
echo "上传失败!";
}
}
}
}
```
使用方法:
```php
$upload = new Upload("uploads/"); // 设置上传目录
$upload->uploadFile($_FILES["fileToUpload"]); // $_FILES["fileToUpload"] 是表单中文件上传字段的名称
```
该类首先在构造函数中设置了上传文件的目标目录,然后在 `uploadFile` 方法中进行了文件大小和类型的检查,并最终将文件上传到目标目录。在实际使用中,你可以根据需要对该类进行扩展和修改。