文件上传类 Upload.class.php
<?php
class Upload {
private $path;
private $n;
private $ext;
private $length;
public function __construct($path = ‘./‘, $n = 3, $ext = [‘jpg‘,‘gif‘,‘png‘,‘rar‘,‘ppt‘,‘doc‘], $length = 20971520) {
$this->path = $path;
$this->n = $n;
$this->ext = $ext;
$this->length = $length;
}
public function up() {
$ufs = $_FILES;
if (count ( $ufs ) <= 0) {
return;
} else {
if (! file_exists ( $this->path )) {
mkdir ( $this->path, 0777, true );
}
$uuu = [ ];
foreach ( $ufs as $k => $v ) {
if (is_array ( $v [‘name‘] )) {
$ns = $v [‘name‘];
$fs = $v [‘tmp_name‘];
$ss = $v [‘size‘];
foreach ( $fs as $kk => $vv ) {
if ($ss [$kk] == 0) {
continue;
}
$uf = iconv ( ‘utf-8‘, ‘gbk‘, $ns [$kk] );
$et = strtolower ( substr ( $uf, strrpos ( $uf, ‘.‘ ) + 1 ) );
if ($this->n == 1) {
$uf = uniqid () . ‘.‘ . $et;
} else if ($this->n == 2) {
$uf = $this->uuid () . ‘.‘ . $et;
} else if ($this->n == 3) {
$nnn = substr ( $uf, 0, strrpos ( $uf, ‘.‘ ) );
$t = 0;
while ( file_exists ( $this->path . $uf ) ) {
$uf = $nnn . (++ $t) . ‘.‘ . $et;
}
}
if (in_array ( $et, $this->ext ) && $ss [$kk] <= $this->length) {
move_uploaded_file ( $vv, $this->path . $uf );
$uuu [] = $uf;
}
}
} else {
if ($v [‘size‘] == 0) {
continue;
}
$uf = iconv ( ‘utf-8‘, ‘gbk‘, $v [‘name‘] );
$et = strtolower ( substr ( $uf, strrpos ( $uf, ‘.‘ ) + 1 ) );
if ($this->n == 1) {
$uf = uniqid () . ‘.‘ . $et;
} else if ($this->n == 2) {
$uf = $this->uuid () . ‘.‘ . $et;
} else if ($this->n == 3) {
$nnn = substr ( $uf, 0, strrpos ( $uf, ‘.‘ ) );
$t = 0;
while ( file_exists ( $this->path . $uf ) ) {
$uf = $nnn . (++ $t) . ‘.‘ . $et;
}
}
if (in_array ( $et, $this->ext ) && $v [‘size‘] <= $this->length) {
move_uploaded_file ( $v [‘tmp_name‘], $this->path . $uf );
$uuu [] = $uf;
}
}
}
return $uuu;
}
}
public function uuid($namespace = ‘‘) {
$guid = $namespace;
$uid = uniqid ( "", true );
$data = $namespace;
$data .= $_SERVER [‘REQUEST_TIME‘];
$data .= $_SERVER [‘HTTP_USER_AGENT‘];
$data .= $_SERVER [‘REMOTE_ADDR‘];
$data .= $_SERVER [‘REMOTE_PORT‘];
$hash = strtoupper ( hash ( ‘ripemd128‘, $uid . $guid . md5 ( $data ) ) );
$guid = substr ( $hash, 0, 8 ) . ‘-‘ . substr ( $hash, 8, 4 ) . ‘-‘ . substr ( $hash, 12, 4 ) . ‘-‘ . substr ( $hash, 16, 4 ) . ‘-‘ . substr ( $hash, 20, 12 );
return $guid;
}
public function __destruct() {
}
}
上传单个文件或者多个文件的html代码 uup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="up.php" method="post" enctype="multipart/form-data">
文件上传:<input type="file" name="f[]" multiple><br><!-- 上传多个文件 -->
<!-- 上传文件:<input type="file" name="f" ><br> 上传单个文件 -->
<input type="submit" value="提交">
</form>
</body>
</html>
引入类和实例化类的代码up.php
<?php
include ‘inc/Upload.class.php‘;
$u=new Upload(‘abc/‘,1);
$uf=$u->up();
echo ‘<pre>‘;
print_r($uf);
时间: 2024-10-05 19:52:56