搜索
首页后端开发php教程php文件上传类与实例(单文件上传、多文件上传)

本文分享一个不错的php文件上传,可以实现单个文件的上传、多个文件的上传功能。有需要的朋友参考下吧。

1,php文件上传类

<?php 
/**
* php 文件上传类
* by bbs.it-home.org
*/
class file_upload {
 var $the_file;
 var $the_temp_file;
 var $upload_dir;
 var $replace;
 var $do_filename_check;
 var $max_length_filename = 100;
 var $extensions;
 var $ext_string;
 var $language;
 var $http_error;
 var $rename_file; // if this var is true the file copy get a new name
 var $file_copy; // the new name
 var $message = array();
 var $create_directory = true;
 
 function file_upload() {
  $this->language = "en"; // choice of en, nl, es
  $this->rename_file = false;
  $this->ext_string = "";
 }
 function show_error_string() {
  $msg_string = "";
  foreach ($this->message as $value) {
   $msg_string .= $value."<br>\n";
  }
  return $msg_string;
 }
 function set_file_name($new_name = "") { // this "conversion" is used for unique/new filenames 
  if ($this->rename_file) {
   if ($this->the_file == "") return;
   $name = ($new_name == "") ? strtotime("now") : $new_name;
   $name = $name.$this->get_extension($this->the_file);
  } else {
   $name = $this->the_file;
  }
  return $name;
 }
 function upload($to_name = "") {
  $new_name = $this->set_file_name($to_name);
  if ($this->check_file_name($new_name)) {
   if ($this->validateExtension()) {
    if (is_uploaded_file($this->the_temp_file)) {
     $this->file_copy = $new_name;
     if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
      $this->message[] = $this->error_text($this->http_error);
      if ($this->rename_file) $this->message[] = $this->error_text(16);
      return true;
     }
    } else {
     $this->message[] = $this->error_text($this->http_error);
     return false;
    }
   } else {
    $this->show_extensions();
    $this->message[] = $this->error_text(11);
    return false;
   }
  } else {
   return false;
  }
 }
 function check_file_name($the_name) {
  if ($the_name != "") {
   if (strlen($the_name) > $this->max_length_filename) {
    $this->message[] = $this->error_text(13);
    return false;
   } else {
    if ($this->do_filename_check == "y") {
     if (preg_match("/^[a-z0-9_]*\.(.){1,5}$/i", $the_name)) {
      return true;
     } else {
      $this->message[] = $this->error_text(12);
      return false;
     }
    } else {
     return true;
    }
   }
  } else {
   $this->message[] = $this->error_text(10);
   return false;
  }
 }
 function get_extension($from_file) {
  $ext = strtolower(strrchr($from_file,"."));
  return $ext;
 }
 function validateExtension() {
  $extension = $this->get_extension($this->the_file);
  $ext_array = $this->extensions;
  if (in_array($extension, $ext_array)) { 
   // check mime type hier too against allowed/restricted mime types (boolean check mimetype)
   return true;
  } else {
   return false;
  }
 }
 // this method is only used for detailed error reporting
 function show_extensions() {
  $this->ext_string = implode(" ", $this->extensions);
 }
 function move_upload($tmp_file, $new_file) {
  umask(0);
  if ($this->existing_file($new_file)) {
   $newfile = $this->upload_dir.$new_file;
   if ($this->check_dir($this->upload_dir)) {
    if (move_uploaded_file($tmp_file, $newfile)) {
     if ($this->replace == "y") {
      //system("chmod 0777 $newfile"); // maybe you need to use the system command in some cases...
      chmod($newfile , 0777);
     } else {
      // system("chmod 0755 $newfile");
      chmod($newfile , 0755);
     }
     return true;
    } else {
     return false;
    }
   } else {
    $this->message[] = $this->error_text(14);
    return false;
   }
  } else {
   $this->message[] = $this->error_text(15);
   return false;
  }
 }
 function check_dir($directory) {
  if (!is_dir($directory)) {
   if ($this->create_directory) {
    umask(0);
    mkdir($directory, 0777);
    return true;
   } else {
    return false;
   }
  } else {
   return true;
  }
 }
 function existing_file($file_name) {
  if ($this->replace == "y") {
   return true;
  } else {
   if (file_exists($this->upload_dir.$file_name)) {
    return false;
   } else {
    return true;
   }
  }
 }
 function get_uploaded_file_info($name) {
  $str = "File name: ".basename($name)."\n";
  $str .= "File size: ".filesize($name)." bytes\n";
  if (function_exists("mime_content_type")) {
   $str .= "Mime type: ".mime_content_type($name)."\n";
  }
  if ($img_dim = getimagesize($name)) {
   $str .= "Image dimensions: x = ".$img_dim[0]."px, y = ".$img_dim[1]."px\n";
  }
  return $str;
 }
 // this method was first located inside the foto_upload extension
 function del_temp_file($file) {
  $delete = @unlink($file); 
  clearstatcache();
  if (@file_exists($file)) { 
   $filesys = eregi_replace("/","\\",$file); 
   $delete = @system("del $filesys");
   clearstatcache();
   if (@file_exists($file)) { 
    $delete = @chmod ($file, 0775); 
    $delete = @unlink($file); 
    $delete = @system("del $filesys");
   }
  }
 }
 // some error (HTTP)reporting, change the messages or remove options if you like.
 function error_text($err_num) {
  switch ($this->language) {
   case "nl":
   $error[0] = "Foto succesvol kopieert.";
   $error[1] = "Het bestand is te groot, controlleer de max. toegelaten bestandsgrootte.";
   $error[2] = "Het bestand is te groot, controlleer de max. toegelaten bestandsgrootte.";
   $error[3] = "Fout bij het uploaden, probeer het nog een keer.";
   $error[4] = "Fout bij het uploaden, probeer het nog een keer.";
   $error[10] = "Selecteer een bestand.";
   $error[11] = "Het zijn alleen bestanden van dit type toegestaan: <b>".$this->ext_string."</b>";
   $error[12] = "Sorry, de bestandsnaam bevat tekens die niet zijn toegestaan. Gebruik alleen nummer, letters en het underscore teken. <br>
Een geldige naam eindigt met een punt en de extensie.";
   $error[13] = "De bestandsnaam is te lang, het maximum is: ".$this->max_length_filename." teken.";
   $error[14] = "Sorry, het opgegeven directory bestaat niet!";
   $error[15] = "Uploading <b>".$this->the_file."...Fout!</b> Sorry, er is al een bestand met deze naam aanwezig.";
   $error[16] = "Het gekopieerde bestand is hernoemd naar <b>".$this->file_copy."</b>.";
   break;
   case "de":
   $error[0] = "Die Datei: <b>".$this->the_file."</b> wurde hochgeladen!"; 
   $error[1] = "Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Server-Konfiguration!"; 
   $error[2] = "Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Klassen-Konfiguration!"; 
   $error[3] = "Die hochzuladende Datei wurde nur teilweise &uuml;bertragen"; 
   $error[4] = "Es wurde keine Datei hochgeladen"; 
   $error[10] = "W&auml;hlen Sie eine Datei aus!."; 
   $error[11] = "Es sind nur Dateien mit folgenden Endungen erlaubt: <b>".$this->ext_string."</b>";
   $error[12] = "Der Dateiname enth&auml;lt ung&uuml;ltige Zeichen. Benutzen Sie nur alphanumerische Zeichen f&uuml;r den Dateinamen 
mit Unterstrich. <br>Ein g&uuml;ltiger Dateiname endet mit einem Punkt, gefolgt von der Endung."; 
   $error[13] = "Der Dateiname &uuml;berschreitet die maximale Anzahl von ".$this->max_length_filename." Zeichen."; 
   $error[14] = "Das Upload-Verzeichnis existiert nicht!"; 
   $error[15] = "Upload <b>".$this->the_file."...Fehler!</b> Eine Datei mit gleichem Dateinamen existiert bereits.";
   $error[16] = "Die hochgeladene Datei ist umbenannt in <b>".$this->file_copy."</b>.";
   break;
   //
   // place here the translations (if you need) from the directory "add_translations"
   //
   default:
   // start http errors
   $error[0] = "File: <b>".$this->the_file."</b> successfully uploaded!";
   $error[1] = "The uploaded file exceeds the max. upload filesize directive in the server configuration.";
   $error[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.";
   $error[3] = "The uploaded file was only partially uploaded";
   $error[4] = "No file was uploaded";
   // end  http errors
   $error[10] = "Please select a file for upload.";
   $error[11] = "Only files with the following extensions are allowed: <b>".$this->ext_string."</b>";
   $error[12] = "Sorry, the filename contains invalid characters. Use only alphanumerical chars and separate parts of the
 name (if needed) with an underscore. <br>A valid filename ends with one dot followed by the extension.";
   $error[13] = "The filename exceeds the maximum length of ".$this->max_length_filename." characters.";
   $error[14] = "Sorry, the upload directory doesn't exist!";
   $error[15] = "Uploading <b>".$this->the_file."...Error!</b> Sorry, a file with this name already exitst.";
   $error[16] = "The uploaded file is renamed to <b>".$this->file_copy."</b>.";
   
  }
  return $error[$err_num];
 }
}
?>

2,单文件上传的例子:

<?php 
include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); //classes is the map where the class file is stored (one above the root) 

$max_size = 1024*250; // the max. size for uploading 
     
$my_upload = new file_upload; 

$my_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/files/new/"; // "files" is the folder for the uploaded files (you have to create this folder) 
$my_upload->extensions = array(".png", ".zip", ".pdf"); // specify the allowed extensions here 
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!) 
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100) 
$my_upload->rename_file = true; 
         
if(isset($_POST['Submit'])) { 
    $my_upload->the_temp_file = $_FILES['upload']['tmp_name']; 
    $my_upload->the_file = $_FILES['upload']['name']; 
    $my_upload->http_error = $_FILES['upload']['error']; 
    $my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true 
    $my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n"; // use this boolean to check for a valid filename 
    $new_name = (isset($_POST['name'])) ? $_POST['name'] : ""; 
    if ($my_upload->upload($new_name)) { // new name is an additional filename information, use this to rename the uploaded file 
        $full_path = $my_upload->upload_dir.$my_upload->file_copy; 
        $info = $my_upload->get_uploaded_file_info($full_path); 
        // ... or do something like insert the filename to the database 
    } 
} 
?>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<title>php文件上传的例子-bbs.it-home.org</title> 
<style type="text/css"> 
<!-- 
label { 
    float:left; 
    display:block; 
    width:120px; 
} 
input { 
    float:left; 
} 
--> 
</style> 
</head> 
<body> 
<h3 id="php文件上传">php文件上传:</h3> 
<p>Max. filesize = <?php echo $max_size; ?> bytes.</p> 
<form name="form1" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
  <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>"><br> 
  <label for="upload">选择文件:</label><input type="file" name="upload" size="30"><br clear="all"> 
  <label for="name">新的文件名称:</label><input type="text" name="name" size="20">  
  (without extension!) <br clear="all"> 
  <label for="replace">是否替换</label><input type="checkbox" name="replace" value="y"><br clear="all"> 
  <label for="check">验证文件名称:</label><input name="check" type="checkbox" value="y" checked><br clear="all"> 
  <input style="margin-left:120px;" type="submit" name="Submit" value="Submit"> 
</form> 
<br clear="all"> 
<p><?php echo $my_upload->show_error_string(); ?></p> 
<?php if (isset($info)) echo "<blockquote>".nl2br($info)."</blockquote>"; ?>  
</body> 
</html>

3,多文件上传的例子

<?php 
include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); //classes is the map where the class file is stored (one above the root) 
//error_reporting(E_ALL); 
$max_size = 1024*100; // the max. size for uploading 

class muli_files extends file_upload { //扩展file_upload类,以实现多文件上传功能
     
    var $number_of_files = 0; 
    var $names_array; 
    var $tmp_names_array; 
    var $error_array; 
    var $wrong_extensions = 0; 
    var $bad_filenames = 0; 
     
    function extra_text($msg_num) { 
        switch ($this->language) { 
            case "de": 
            // add you translations here 
            break; 
            default: 
            $extra_msg[1] = "Error for: <b>".$this->the_file."</b>"; 
            $extra_msg[2] = "You have tried to upload ".$this->wrong_extensions." files with a bad extension, the following extensions
 are allowed: <b>".$this->ext_string."</b>"; 
            $extra_msg[3] = "Select at least on file."; 
            $extra_msg[4] = "Select the file(s) for upload."; 
            $extra_msg[5] = "You have tried to upload <b>".$this->bad_filenames." files</b> with invalid characters inside the filename."; 
        } 
        return $extra_msg[$msg_num]; 
    } 
    // this method checkes the number of files for upload 
    // this example works with one or more files 
    function count_files() { 
        foreach ($this->names_array as $test) { 
            if ($test != "") { 
                $this->number_of_files++; 
            } 
        } 
        if ($this->number_of_files > 0) { 
            return true; 
        } else { 
            return false; 
        }  
    } 
    function upload_multi_files () { 
        $this->message = ""; 
        if ($this->count_files()) { 
            foreach ($this->names_array as $key => $value) {  
                if ($value != "") { 
                    $this->the_file = $value; 
                    $new_name = $this->set_file_name(); 
                    if ($this->check_file_name($new_name)) { 
                        if ($this->validateExtension()) { 
                            $this->file_copy = $new_name; 
                            $this->the_temp_file = $this->tmp_names_array[$key]; 
                            if (is_uploaded_file($this->the_temp_file)) { 
                                if ($this->move_upload($this->the_temp_file, $this->file_copy)) { 
                                    $this->message[] = $this->error_text($this->error_array[$key]); 
                                    if ($this->rename_file) $this->message[] = $this->error_text(16); 
                                    sleep(1); // wait a seconds to get an new timestamp (if rename is set) 
                                } 
                            } else { 
                                $this->message[] = $this->extra_text(1); 
                                $this->message[] = $this->error_text($this->error_array[$key]); 
                            } 
                        } else { 
                            $this->wrong_extensions++; 
                        } 
                    } else { 
                        $this->bad_filenames++; 
                    } 
                }  
            } 
            if ($this->bad_filenames > 0) $this->message[] = $this->extra_text(5); 
            if ($this->wrong_extensions > 0) { 
                $this->show_extensions(); 
                $this->message[] = $this->extra_text(2); 
            } 
        } else { 
            $this->message[] = $this->extra_text(3); 
        } 
    } 
} 

$multi_upload = new muli_files; 

$multi_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/files/"; // "files" is the folder for the uploaded files (you have to create this folder) 
$multi_upload->extensions = array(".png", ".zip"); // specify the allowed extensions here 
$multi_upload->message[] = $multi_upload->extra_text(4); // a different standard message for multiple files 
//$multi_upload->rename_file = true; // set to "true" if you want to rename all files with a timestamp value 
$multi_upload->do_filename_check = "y"; // check filename ... 
         
if(isset($_POST['Submit'])) { 
    $multi_upload->tmp_names_array = $_FILES['upload']['tmp_name']; 
    $multi_upload->names_array = $_FILES['upload']['name']; 
    $multi_upload->error_array = $_FILES['upload']['error']; 
    $multi_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true 
    $multi_upload->upload_multi_files(); 
} 
?>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<title>php多文件上传的例子-bbs.it-home.org</title> 
<style type="text/css"> 
<!-- 
label { 
    width: 80px; 
} 
input { 
    margin-bottom:3px; 
    margin-left:5px; 
} 
--> 
</style> 
</head> 

<body> 
<h3 id="PHP-多文件上传">PHP 多文件上传:</h3> 
<p>Max. filesize = <?php echo $max_size; ?> bytes. (each) </p> 
<form name="form1" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
  <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>"> 
  <label for="upload[]">File 1:</label> 
  <input type="file" name="upload[]" size="30"><br> 
  <label for="upload[]">File 2:</label> 
  <input type="file" name="upload[]" size="30"><br> 
  <label for="upload[]">File 3:</label> 
  <input type="file" name="upload[]" size="30"><br> 
  <!-- Add here more file fields if you need. --> 
  Replace files?  
  <input type="checkbox" name="replace" value="y"> 
  <input type="submit" name="Submit" value="上传文件"> 
</form> 
<p><?php echo $multi_upload->show_error_string(); ?></p> 
</body> 
</html>


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

您应该多久再生一次会话ID?您应该多久再生一次会话ID?Apr 23, 2025 am 12:03 AM

会话ID应在登录时、敏感操作前和每30分钟定期重新生成。1.登录时重新生成会话ID可防会话固定攻击。2.敏感操作前重新生成提高安全性。3.定期重新生成降低长期利用风险,但需权衡用户体验。

如何在PHP中设置会话cookie参数?如何在PHP中设置会话cookie参数?Apr 22, 2025 pm 05:33 PM

在PHP中设置会话cookie参数可以通过session_set_cookie_params()函数实现。1)使用该函数设置参数,如过期时间、路径、域名、安全标志等;2)调用session_start()使参数生效;3)根据需求动态调整参数,如用户登录状态;4)注意设置secure和httponly标志以提升安全性。

在PHP中使用会议的主要目的是什么?在PHP中使用会议的主要目的是什么?Apr 22, 2025 pm 05:25 PM

在PHP中使用会话的主要目的是维护用户在不同页面之间的状态。1)会话通过session_start()函数启动,创建唯一会话ID并存储在用户cookie中。2)会话数据保存在服务器上,允许在不同请求间传递数据,如登录状态和购物车内容。

您如何在子域中分享会议?您如何在子域中分享会议?Apr 22, 2025 pm 05:21 PM

如何在子域名间共享会话?通过设置通用域名的会话cookie实现。1.在服务器端设置会话cookie的域为.example.com。2.选择合适的会话存储方式,如内存、数据库或分布式缓存。3.通过cookie传递会话ID,服务器根据ID检索和更新会话数据。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),