当前位置:  编程技术>php
本页文章导读:
    ▪php 验证类(Email、数字、字符串等的验证)      php 验证类的代码,如下: <?php /** * 基于服务器端的输入验证 * 包括 Email、数字、日期等的验证 * 编辑整理: www. */ class Validation { //检测电子邮件格式是否正确,返回true或false fu.........
    ▪php文件上传类upload_class的扩展类及示例      分享一个上传图片文件的php扩展类,基于前文:php文件上传类与实例的一个扩展。 主要用于上传图片文件。 代码: <?php /** * php图片上传类 * 基类:file_upload * 编辑:www. */ include ($_SE.........
    ▪php文件上传类与实例(单文件上传、多文件上传)      1,php文件上传类 <?php /** * php 文件上传类 * by www. */ 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; .........

[1]php 验证类(Email、数字、字符串等的验证)
    来源: 互联网  发布时间: 2013-12-24

php 验证类的代码,如下:

<?php 
/**
* 基于服务器端的输入验证
* 包括 Email、数字、日期等的验证
* 编辑整理: www.
*/

class Validation 
{ 
//检测电子邮件格式是否正确,返回true或false
function is_email($email) 
    { 
        if(!preg_match("/^[A-Za-z0-9\._\-+]+@[A-Za-z0-9_\-+]+(\.[A-Za-z0-9_\-+]+)+$/",$email)) 
            return false; 
        return true; 
    } 
// End of is_email Function 

//检查给定的数字符号/无符号数
//返回true或false。
    function is_number($number) 
    { 
        if(!preg_match("/^\-?\+?[0-9e1-9]+$/",$number)) 
            return false; 
        return true; 
    } 
// End of is_number Function 

//检查否无符号数字
//返回true或false
function is_unsign_number($number) 
    { 
        if(!preg_match("/^\+?[0-9]+$/",$number)) 
            return false; 
        return true; 
    } 
// End of is_unsign_number Function 
     
//检查给定的字符串是否数字、字母等的组合
//返回true或false
    function is_alpha_numeric($str) 
    { 
        if(!preg_match("/^[A-Za-z0-9 ]+$/",$str)) 
            return false; 
        return true; 
    } 
// End of is_alpha_numeric Function 

//这个函数检查给定的日期是有效或无效。
//返回true或false。
function is_date($d) 
    { 
        if(!preg_match("/^(\d){1,2}[-\/](\d){1,2}[-\/]\d{4}$/",$d,$matches)) 
            return -1;//Bad Date Format 
        $T = split("[-/\\]",$d); 
        $MON=array(0,31,28,31,30,31,30,31,31,30,31,30,31); 
        $M = $T[0]; 
        $D = $T[1]; 
        $Y = $T[2]; 
        return $D>0 && ($D<=$MON[$M] ||    $D==29 && $Y%4==0 && ($Y%100!=0 || $Y%400==0));  
    } 
    //End of is_data function 
}
?>

2,php 验证类的调用示例:

<?php 
require("validations.inc.php"); 

$val=new Validation; 

if($val->is_email($_POST['email'])) 
    echo "Email is Valid!"; 
else 
    echo "Not a valid email"; 
echo "<br>"; 

if($val->is_number($_POST['number'])) 
    echo "number is Valid!"; 
else 
    echo "Not a valid number"; 
echo "<br>"; 

if($val->is_alpha_numeric($_POST['String'])) 
    echo "String is Valid!"; 
else 
    echo "Not a valid String"; 
echo "<br>"; 
if($val->is_date($_POST['date'])>0) 
    echo "date is Valid!"; 
else 
    echo "Not a valid date"; 
echo "<br>"; 

?> 
<form name='form1' method='post' action=""> 
<table> 
<tr><td>Enter Email :</td><td><input name='email'></td></tr> 
<tr><td>Enter Number :</td><td><input name='number'></td></tr> 
<tr><td>Enter Date :</td><td><input name='date'>(mm-dd-yyyy)</td></tr> 
<tr><td>Enter String :</td><td><input name='String'></td></tr> 
<tr><td>Press Submit :</td><td><input name='Submit' type='submit'></td></tr> 
</table> 
</form>

    
[2]php文件上传类upload_class的扩展类及示例
    来源: 互联网  发布时间: 2013-12-24

分享一个上传图片文件的php扩展类,基于前文:php文件上传类与实例的一个扩展。
主要用于上传图片文件。

代码:

<?php 
/**
* php图片上传类
* 基类:file_upload
* 编辑:www.
*/
include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); 
error_reporting(E_ALL); 
ini_set("memory_limit", "64M"); 
set_time_limit(60); 

class Foto_upload extends file_upload { 
     
    var $x_size; 
    var $y_size; 
    var $x_max_size = 300; 
    var $y_max_size = 200; 
    var $x_max_thumb_size = 110; 
    var $y_max_thumb_size = 88; 
    var $thumb_folder; 
    var $foto_folder; 
    var $larger_dim; 
    var $larger_curr_value; 
    var $larger_dim_value; 
    var $larger_dim_thumb_value; 
     
    var $use_image_magick = true; // switch between true and false 
    // I suggest to use ImageMagick on Linux/UNIX systems, it works on windows too, but it's hard to configurate 
    // check your existing configuration by your web hosting provider 
     
    function process_image($landscape_only = false, $create_thumb = false, $delete_tmp_file = false, $compression = 85) { 
        $filename = $this->upload_dir.$this->file_copy; 
        $this->check_dir($this->thumb_folder); // run these checks to create not existing directories 
        $this->check_dir($this->foto_folder); // the upload dir is created during the file upload (if not already exists) 
        $thumb = $this->thumb_folder.$this->file_copy; 
        $foto = $this->foto_folder.$this->file_copy; 
        if ($landscape_only) { 
            $this->get_img_size($filename); 
            if ($this->y_size > $this->x_size) { 
                $this->img_rotate($filename, $compression); 
            } 
        } 
        $this->check_dimensions($filename); // check which size is longer then the max value 
        if ($this->larger_curr_value > $this->larger_dim_value) { 
            $this->thumbs($filename, $foto, $this->larger_dim_value, $compression); 
        } else { 
            copy($filename, $foto); 
        } 
        if ($create_thumb) { 
            if ($this->larger_curr_value > $this->larger_dim_thumb_value) { 
                $this->thumbs($filename, $thumb, $this->larger_dim_thumb_value, $compression); // finally resize the image 
            } else { 
                copy($filename, $thumb); 
            } 
        } 
        if ($delete_tmp_file) $this->del_temp_file($filename); // note if you delete the tmp file the check if a file exists will not work 
    } 
    function get_img_size($file) { 
        $img_size = getimagesize($file); 
        $this->x_size = $img_size[0]; 
        $this->y_size = $img_size[1]; 
    } 
    function check_dimensions($filename) { 
        $this->get_img_size($filename); 
        $x_check = $this->x_size - $this->x_max_size; 
        $y_check = $this->y_size - $this->y_max_size; 
        if ($x_check < $y_check) { 
            $this->larger_dim = "y"; 
            $this->larger_curr_value = $this->y_size; 
            $this->larger_dim_value = $this->y_max_size; 
            $this->larger_dim_thumb_value = $this->y_max_thumb_size; 
        } else { 
            $this->larger_dim = "x"; 
            $this->larger_curr_value = $this->x_size; 
            $this->larger_dim_value = $this->x_max_size; 
            $this->larger_dim_thumb_value = $this->x_max_thumb_size; 
        } 
    } 
    function img_rotate($wr_file, $comp) { 
        $new_x = $this->y_size; 
        $new_y = $this->x_size; 
        if ($this->use_image_magick) { 
            exec(sprintf("mogrify -rotate 90 -quality %d %s", $comp, $wr_file)); 
        } else { 
            $src_img = imagecreatefromjpeg($wr_file); 
            $rot_img = imagerotate($src_img, 90, 0); 
            $new_img = imagecreatetruecolor($new_x, $new_y); 
            imageantialias($new_img, TRUE); 
            imagecopyresampled($new_img, $rot_img, 0, 0, 0, 0, $new_x, $new_y, $new_x, $new_y); 
            imagejpeg($new_img, $this->upload_dir.$this->file_copy, $comp); 
        } 
    } 
    function thumbs($file_name_src, $file_name_dest, $target_size, $quality = 80) { 
        //print_r(func_get_args()); 
        $size = getimagesize($file_name_src); 
        if ($this->larger_dim == "x") { 
            $w = number_format($target_size, 0, ',', ''); 
            $h = number_format(($size[1]/$size[0])*$target_size,0,',',''); 
        } else { 
            $h = number_format($target_size, 0, ',', ''); 
            $w = number_format(($size[0]/$size[1])*$target_size,0,',',''); 
        } 
        if ($this->use_image_magick) { 
            exec(sprintf("convert %s -resize %dx%d -quality %d %s", $file_name_src, $w, $h, $quality, $file_name_dest)); 
        } else { 
            $dest = imagecreatetruecolor($w, $h); 
            imageantialias($dest, TRUE); 
            $src = imagecreatefromjpeg($file_name_src); 
            imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); 
            imagejpeg($dest, $file_name_dest, $quality); 
        } 
    } 
} 

$max_size = 1024*1024; // the max. size for uploading (~1MB) 
define("MAX_SIZE", $max_size); 
$foto_upload = new Foto_upload; 

$foto_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/files/"; // "files" is the folder for the uploaded files (you have to create these folder) 
$foto_upload->foto_folder = $_SERVER['DOCUMENT_ROOT']."/files/photo/"; 
$foto_upload->thumb_folder = $_SERVER['DOCUMENT_ROOT']."/files/thumb/"; 
$foto_upload->extensions = array(".jpg"); // specify the allowed extension(s) here 
$foto_upload->language = "en"; 
$foto_upload->x_max_size = 300; 
$foto_upload->y_max_size = 200; 
$foto_upload->x_max_thumb_size = 120; 
$foto_upload->y_max_thumb_size = 150; 
         
if (isset($_POST['Submit']) && $_POST['Submit'] == "Upload") { 
    $foto_upload->the_temp_file = $_FILES['upload']['tmp_name']; 
    $foto_upload->the_file = $_FILES['upload']['name']; 
    $foto_upload->http_error = $_FILES['upload']['error']; 
    $foto_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true 
    $foto_upload->do_filename_check = "n";  
    if ($foto_upload->upload()) { 
        $foto_upload->process_image(false, true, 80); 
        $foto_upload->message[] = "Processed foto: ".$foto_upload->file_copy."!"; // "file_copy is the name of the foto" 
    } 
} 
$error = $foto_upload->show_error_string(); 
?>

2,上传图片的调用示例

<!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图片上传类的调用示例-www.</title> 
<style type="text/css"> 
<!-- 
body { 
    text-align:center; 
} 
label { 
    margin:0; 
    float:left; 
    display:block; 
    width:120px; 
} 
#main { 
    width:350px; 
    margin:0 auto; 
    padding:20px 0; 
    text-align:left; 
} 
--> 
</style> 
</head> 
<body> 
<div id="main"> 
  <h1>上传图片</h1> 
  <form action="/blog_article/</php echo $_SERVER[.html'PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> 
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>"><br> 
    <div> 
      <label for="upload">选择图片文件:</label> 
    <input type="file" name="upload" id="upload" size="35"></div> 
    <div> 
      <label for="replace">替换旧的图片文件吗?</label> 
    <input type="checkbox" name="replace" value="y"></div> 
    <p ><input type="submit" name="Submit" id="Submit" value="上传图片"> 
    </p> 
  </form> 
  <p><?php echo $error; ?></p> 
</div>   
</body> 
</html>

    
[3]php文件上传类与实例(单文件上传、多文件上传)
    来源: 互联网  发布时间: 2013-12-24

1,php文件上传类

<?php 
/**
* php 文件上传类
* by www.
*/
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文件上传的例子-www.</title> 
<style type="text/css"> 
<!-- 
label { 
    float:left; 
    display:block; 
    width:120px; 
} 
input { 
    float:left; 
} 
--> 
</style> 
</head> 
<body> 
<h3>php文件上传:</h3> 
<p>Max. filesize = <?php echo $max_size; ?> bytes.</p> 
<form name="form1" enctype="multipart/form-data" method="post" action="/blog_article/</php echo $_SERVER[.html'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  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多文件上传的例子-www.</title> 
<style type="text/css"> 
<!-- 
label { 
    width: 80px; 
} 
input { 
    margin-bottom:3px; 
    margin-left:5px; 
} 
--> 
</style> 
</head> 

<body> 
<h3>PHP 多文件上传:</h3> 
<p>Max. filesize = <?php echo $max_size; ?> bytes. (each) </p> 
<form name="form1" enctype="multipart/form-data" method="post" action="/blog_article/</php echo $_SERVER[.html'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>

    
最新技术文章:
▪PHP函数microtime()时间戳的定义与用法
▪PHP单一入口之apache配置内容
▪PHP数组排序方法总结(收藏)
▪php数组排序方法大全(脚本学堂整理奉献)
▪php数组排序的几个函数(附实例)
▪php二维数组排序(实例)
▪php根据键值对二维数组排序的小例子
▪php验证码(附截图)
▪php数组长度的获取方法(三个实例)
▪php获取数组长度的方法举例
▪判断php数组维度(php数组长度)的方法
▪php获取图片的exif信息的示例代码
▪PHP 数组key长度对性能的影响实例分析
▪php函数指定默认值的方法示例
▪php提交表单到当前页面、提交表单后页面重定...
▪php四舍五入的三种实现方法
▪php获得数组长度(元素个数)的方法
▪php日期函数的简单示例代码
▪php数学函数的简单示例代码
移动开发 iis7站长之家
▪php文件下载代码(多浏览器兼容、支持中文文...
▪php实现文件下载、支持中文文件名的示例代码...
▪php文件下载(防止中文文件名乱码)的示例代码
▪解决PHP文件下载时中文文件名乱码的问题
▪php数组去重(一维、二维数组去重)的简单示例
▪php小数点后取两位的三种实现方法
▪php Redis 队列服务的简单示例
▪PHP导出excel时数字变为科学计数的解决方法
▪PHP数组根据值获取Key的简单示例
▪php数组去重的函数代码示例
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3