A _php tutorial on how to handle common form multiple file uploads in PHP

Source: Internet
Author: User
However, some cases only need to pass a few files, and the file volume is not too large, in this case the use of components is a bit sledgehammer to kill the chicken feeling, through the HTML comes with the form can achieve the required functions, the key is the processing of the background receiving program.

PHP processing upload is very convenient, upload the file information through the server automatically processed into the $_files array, developers only need to use the built-in processing function simple operation can be. The ASP developer is not so fortunate, the official does not provide the direct processing method, needs the developer to design, then needs the developer to understand the IIS to Enctype= "Multipart/form-data" the form Processing Way, IIS Enctype= " Multipart/form-data "Form submitted data is stored in binary data, returned to the developer in binary format, developers need to use LenB, MidB byte processing function to analyze the obtained upload content, the client sends the specific form data format, can understand the next HTTP Knowledge of RFC1867 protocol transfer format.

Here's how I handle multiple file uploads, including PHP and ASP two versions.

Php:website_dirroot on behalf of the site root directory:
Copy CodeThe code is as follows:
/*
* Class: File Upload Class
* AUTHOR:51JS.COM-ZMM
* date:2011.1.20
* email:304924248@qq.com
* blog:http://www.cnblogs.com/cnzmm/
*/

Class Upload {
Public $up _ext=array (), $up _max=5210, $up _dir;
Private $up _name, $up _rename=true, $up _num=0, $up _files=array (), $up _ret=array ();

function __construct ($name, $ext =array (), $rename =true) {
if (!empty ($name)) {
$this->up_name = $name;
!empty ($ext) && $this->up_ext = $ext;
$this->up_rename = $rename;
$this->up_dir = Website_dirroot.
$GLOBALS [' Cfg_upload_path '];
$this->initupload ();
} else {
Exit (' Upload file domain name is empty, initialization failed! ');
}
}

Private Function Initupload () {
if (Is_array ($_files[$this->up_name])) {
$up _arr = count ($_files[$this->up_name]);
$up _all = count ($_files[$this->up_name], 1);
$up _cnt = ($up _all-$up _arr)/$up _arr;
for ($i = 0; $i < $up _cnt; $i + +) {
if ($_files[$this->up_name][' ERROR ' [$i]! = 4) {
$this->up_files[] = Array (
' Tmp_name ' = $_files[$this->up_name][' tmp_name ' [$i],
' Name ' = $_files[$this->up_name][' name ' [$i],
' Type ' = $_files[$this->up_name][' type ' [$i],
' Size ' = $_files[$this->up_name][' size ' [$i],
' Error ' = $_files[$this->up_name][' ERROR ' [$i]
);
}
}
$this->up_num = count ($this->up_files);
} else {
if (Isset ($_files[$this->up_name])) {
$this->up_files = Array (
' Tmp_name ' + $_files[$this->up_name][' tmp_name '),
' Name ' = $_files[$this->up_name][' name '),
' Type ' = $_files[$this->up_name][' type '),
' Size ' = $_files[$this->up_name][' size '),
' Error ' = $_files[$this->up_name][' ERROR ']
);
$this->up_num = 1;
} else {
Exit (' I didn't find a file to upload! ');
}
}

$this->chkupload ();
}

Private Function Chkupload () {
if (Empty ($this->up_ext)) {
$up _mime = Array (' image/wbmp ', ' image/bmp ', ' image/gif ', ' image/pjpeg ', ' image/x-png ');
foreach ($this->up_files as $up _file) {
$up _ALLW = false;
foreach ($up _mime as $mime) {
if ($up _file[' type '] = = $mime) {
$up _ALLW = true; Break
}
}
! $up _allw && exit (' Do not allow uploads '. $up _file[' type '). ' Format the file! ');

if ($up _file[' size ']/1024x768 > $this->up_max) {
Exit (' Do not allow uploads greater than '. $this->up_max. ' K ' File! ');
}
}
} else {
foreach ($this->up_files as $up _file) {
$up _ext = end (Explode ('. ', $up _file[' name '));

$up _ALLW = false;
foreach ($this->up_ext as $ext) {
if ($up _ext = = $ext) {
$up _ALLW = true; Break
}
}
! $up _allw && exit (' Do not allow upload. ') $up _ext. ' Format file Now! ');

if ($up _file[' size ']/1024x768 > $this->up_max) {
Exit (' Do not allow uploads greater than '. $this->up_max. ' K ' File! ');
}
}
}

$this->uploading ();
}

Private function uploading () {
if (IO::D ircreate ($this->up_dir)) {
if (chmod ($this->up_dir, 0777)) {
if (!empty ($this->up_files)) {
foreach ($this->up_files as $up _file) {
if (Is_uploaded_file ($up _file[' Tmp_name ')) {
$file _name = $up _file[' name '];
if ($this->up_rename) {
$file _ext = end (Explode ('. ', $file _name));
$file _rnd = substr (MD5 (UNIQID ()), Mt_rand (0, 26), 6);
$file _name = Date (' Ymdhis '). ' _ '. $file _rnd. '. $file _ext;
}
$file _name = $this->up_dir. '/'. $file _name;

if (Move_uploaded_file ($up _file[' tmp_name '), $file _name)) {
$this->up_ret[] = Str_replace (Website_dirroot, ", $file _name);
} else {
Exit (' File upload failed! ');
}
}
}
}
} else {
Exit (' Write permission is not turned on! ');
}
} else {
Exit (' Upload directory creation failed! ');
}
}

Public Function Getupload () {
return empty ($this->up_ret)? False: $this->up_ret;
}

function __destruct () {}
}
?>


Asp:
Copy CodeThe code is as follows:
<%
Class Multiupload

REM public-variant

Public Form, isfinished
Private Bvbcrlf, Bseparate, fpassed, FormData, FileType, FileSize, FolderPath, _
Frename, Fimgonly, ItemCount, ChunkSize, Btime, Serrors, Sauthor, sversion
Private Itemstart (), Itemlength (), Datastart (), datalength (), ItemName (), ItemData (), Extenarr (), Httparr ()

REM class-initialize

Private Sub Class_Initialize
Call Initvariant
Server.ScriptTimeout = 1800
Set Form = Server.CreateObject ("Scripting.Dictionary")
Sauthor = "51JS.COM-ZMM"
Sversion = "Multiupload Class 3.0"
End Sub

REM class-attributes

Public Property Let Allowtype (ByVal stype)
Dim regEx
Set regEx = New RegExp
Regex.pattern = "^ (\w+\|) *\w+$ "
Regex.global = False
Regex.ignorecase = True
If regex.test (stype) then FileType = "|" & Ucase (stype) & "|"
Set regEx = Nothing
End Property

Public Property Let MaxSize (ByVal ssize)
If IsNumeric (ssize) Then fileSize = CDBL (FormatNumber (CCur (Ssize), 2))
End Property

Public Property Let Savefolder (ByVal sfolder)
FolderPath = Sfolder
End Property

Public Property Let commonpassed (ByVal bcheck)
fpassed = bcheck
End Property

Public Property Let Filerenamed (ByVal brename)
Frename = Brename
End Property

Public Property Let Fileisallimg (ByVal bonly)
Fimgonly = bonly
End Property

Public Property Get Savefolder
Savefolder = FolderPath
End Property

Public Property Get Filerenamed
filerenamed = Frename
End Property

Public Property Get Fileisallimg
Fileisallimg = fimgonly
End Property

Public Property Get Errmessage
Errmessage = Serrors
End Property

Public Property Get Clsauthor
Clsauthor = Sauthor
End Property

Public Property Get Clsversion
Clsversion = Sversion
End Property

REM Class-methods

Private Function Initvariant
isfinished = False
Bvbcrlf = Strtobyte (VbCrlf & VbCrlf)
Bseparate = Strtobyte (String (29, "-"))
fpassed = False
FileType = "*"
FileSize = "*"
Frename = True
Fimgonly = True
ItemCount = 0
ChunkSize = 1024 * 128
Btime = Now
Serrors = ""
End Function

Public Function Getuploaddata
Dim curread:curread = 0
Dim Datalen:datalen = request.totalbytes
Dim appname:appname = "PROGRESS" & Iptonum (GETCLIENTIPADDR)
Dim streamtmp
Set streamtmp = Server.CreateObject ("ADODB. Stream ")
Streamtmp.type = 1
Streamtmp.open
Do While Curread < Datalen
Dim Partlen:partlen = chunkSize
If Partlen + curread > datalen then Partlen = Datalen-curread
Streamtmp.write Request.BinaryRead (Partlen)
Curread = Curread + Partlen
Letprogress AppName, Array (Curread, Datalen, DateDiff ("s", Btime, now), FolderPath)
Loop
streamtmp.position = 0
FormData = Streamtmp.read (datalen)
Streamtmp.close
Set streamtmp = Nothing
Call Itemposition
End Function

Private Function letprogress (byVal sName, ByVal Varr)
Application.value (SName) = Join (Varr, "|")
End Function

Private Function delprogress
Application.Contents.Remove ("PROGRESS" & Iptonum (GETCLIENTIPADDR))
End Function

Private Function itemposition
Dim IStart, Ilength:istart = 1
Do Until InStrB (IStart, formData, bseparate) = 0
IStart = InStrB (IStart, FormData, bseparate) + LenB (bseparate) + 14
Ilength = InStrB (IStart, FormData, bseparate)-iStart-2
If Abs (IStart + 2-lenb (formData)) > 2 Then
ReDim Preserve Itemstart (itemCount)
ReDim Preserve itemlength (itemCount)
Itemstart (itemCount) = IStart
Itemlength (itemCount) = Ilength
ItemCount = ItemCount + 1
End If
Loop
Call Fillitemvalue
End Function

Private Function Fillitemvalue
Dim Datapart, Binfor
Dim Istart:istart = 1
Dim icount:icount = 0
Dim Icheck:icheck = strtobyte ("filename")
For i = 0 to ItemCount-1
ReDim Preserve ItemName (iCount)
ReDim Preserve ItemData (iCount)
ReDim Preserve Extenarr (iCount)
ReDim Preserve Httparr (iCount)
ReDim Preserve Datastart (iCount)
ReDim Preserve datalength (iCount)
Datapart = MidB (FormData, Itemstart (i), itemlength (i))
IStart = InStrB (1, Datapart, ChrB (34)) + 1
Ilength = InStrB (IStart, Datapart, ChrB)-IStart
ItemName (ICount) = Getitemname (MidB (Datapart, IStart, Ilength))
IStart = InStrB (1, Datapart, BVBCRLF) + 4
Ilength = LenB (datapart)-IStart + 1
If InStrB (1, Datapart, ICheck) > 0 Then
Binfor = MidB (Datapart, 1, iStart-5)
Extenarr (ICount) = Fileextenname (binfor)
Httparr (ICount) = Gethttpcontent (binfor)
If IsNothing (Extenarr (iCount)) Then
ItemData (ICount) = ""
Datastart (ICount) = ""
Datalength (ICount) = ""
Else
If Mid (FolderPath, Len (FolderPath)-1) = "/" Then
If Frename Then
ItemData (ICount) = FolderPath & Getrandomname (6) & Extenarr (ICount)
Else
ItemData (ICount) = FolderPath & Getclientname (binfor) & Extenarr (ICount)
End If
Else
If Frename Then
ItemData (ICount) = FolderPath & "/" & Getrandomname (6) & Extenarr (ICount)
Else
ItemData (ICount) = FolderPath & "/" & Getclientname (binfor) & Extenarr (ICount)
End If
End If
Datastart (ICount) = Itemstart (i) + iStart-2
Datalength (iCount) = Ilength
End If
Else
Extenarr (ICount) = ""
Httparr (ICount) = ""
ItemData (ICount) = Bytetostr (MidB (Datapart, IStart, Ilength))
Datastart (ICount) = ""
Datalength (ICount) = ""
End If
ICount = ICount + 1
Next
Call Itemtocoll
End Function

Private Function getitemname (byVal bname)
Getitemname = Bytetostr (bname)
End Function

Private Function Itemtocoll
For i = 0 to ItemCount-1
If not form.exists (ItemName (i)) then
Form.add ItemName (i), ItemData (i)
End If
Next
End Function

Private Function fileextenname (ByVal binfor)
Dim Pcontent, RegEx
Pcontent = Getclientpath (binfor)
If IsNothing (pcontent) Then
Fileextenname = ""
Else
Set regEx = New RegExp
Regex.pattern = "^.+ (\.[ ^\.] +)$"
Regex.global = False
Regex.ignorecase = True
Fileextenname = Regex.Replace (pcontent, "$")
Set regEx = Nothing
End If
End Function

Private Function gethttpcontent (ByVal binfor)
Dim Sinfor, RegEx
Sinfor = Bytetostr (binfor)
Set regEx = New RegExp
Regex.pattern = "^[\s\s]+content-type: ([\s\s]+) $"
Regex.global = False
Regex.ignorecase = True
Gethttpcontent = Trim (Regex.Replace (sinfor, "$"))
Set regEx = Nothing
End Function

Private Function getrandomname (ByVal slen)
Dim regEx, Stemp, arrfields, n = 0
Set regEx = New RegExp
Regex.pattern = "[^\d]+"
Regex.global = True
Regex.ignorecase = True
Stemp = Regex.Replace (now, "") & "-"
Set regEx = Nothing
Arrfields = Array ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", _
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", _
"K", "L", "M", "N", "O", "P", "Q", "R", "s", "T", _
"U", "V", "w", "X", "Y", "Z", "A", "B", "C", "D", _
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", _
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", _
"Y", "Z")
Randomize
Do While n < Slen
Stemp = stemp & CStr (arrfields (* Rnd))
n = n + 1
Loop
Getrandomname = stemp
End Function

Private Function getclientname (ByVal binfor)
Dim Pcontent, RegEx
Pcontent = Getclientpath (binfor)
If IsNothing (pcontent) Then
Getclientname = ""
Else
Set regEx = New RegExp
Regex.pattern = "^.*\\ ([^\.] *)[^\\]+$"
Regex.global = False
Regex.ignorecase = True
Getclientname = Regex.Replace (pcontent, "$")
Set regEx = Nothing
End If
End Function

Private Function Getclientpath (ByVal binfor)
Dim sinfor, Pstart, Plength, pcontent
Sinfor = Bytetostr (binfor)
Pstart = INSTR (1, sinfor, "Filename=" & Chr (34)) + 10
Plength = InStr (Pstart, Sinfor, Chr)-Pstart
Pcontent = Mid (Sinfor, Pstart, Plength)
Getclientpath = Pcontent
End Function

Public Function Saveuploadfile
Dim isvalidate
Dim FilePath, Ostreamget, Ostreamput
Isvalidate = fpassed and Checkfile
If Isvalidate Then
For i = 0 to ItemCount-1
If not IsNothing (Datastart (i)) and is IsNothing (datalength (i)) then
If datalength (i) = 0 Then
ItemData (i) = ""
Else
FilePath = Server.MapPath (ItemData (i))
If CreateFolder ("|", ParentFolder (FilePath)) Then
Set ostreamget = Server.CreateObject ("ADODB. Stream ")
Ostreamget.type = 1
Ostreamget.mode = 3
Ostreamget.open
Ostreamget.write FormData
Ostreamget.position = Datastart (i)
Set ostreamput = Server.CreateObject ("ADODB. Stream ")
Ostreamput.type = 1
Ostreamput.mode = 3
Ostreamput.open
Ostreamput.write Ostreamget.read (datalength (i))
Ostreamput.savetofile FilePath, 2
Ostreamget.close
Set Ostreamget = Nothing
Ostreamput.close
Set Ostreamput = Nothing
End If
End If
End If
Next
isfinished = True
Else
isfinished = False
End If
End Function

Private Function Checkfile
Dim Oboolean:oboolean = True
Checkfile = Oboolean and Checktype and Checksize
End Function

Private Function Checktype
Dim Oboolean:oboolean = True
If FileType = "*" Then
Oboolean = Oboolean and True
Else
For i = 0 to ItemCount-1
If not IsNothing (Extenarr (i)) then
If InStr (1, fileType, "|" & Ucase (Mid (Extenarr (i), 2) & "|") > 0 Then
If Fimgonly Then
Dim Sallow:sallow = "| Gif| Pjpeg| X-png| Bmp| "
Dim Acheck:acheck = Split (UCase (Httparr (i)), "/")
Dim Icheck:icheck = "|" & Acheck (Ubound (Acheck)) & "|"
If InStr (1, Sallow, ICheck, 1) > 0 Then
Oboolean = Oboolean and True
Else
Serrors = serrors & "Forms [" & ItemName (i) & "] File format errors! \ n "& _
"Supported formats:" & Replace (Mid (FileType, 2, Len (FileType)-1), "|", "") & "\ n"
Oboolean = Oboolean and False
End If
Else
Oboolean = Oboolean and True
End If
Else
Serrors = serrors & "Forms [" & ItemName (i) & "] File format errors! \ n "& _
"Supported formats:" & Replace (Mid (FileType, 2, Len (FileType)-1), "|", "") & "\ n"
Oboolean = Oboolean and False
End If
End If
Next
End If
Checktype = Oboolean
End Function

Private Function Checksize
Dim Oboolean:oboolean = True
If fileSize = "*" Then
Oboolean = Oboolean and True
Else
For i = 0 to ItemCount-1
If not IsNothing (datalength (i)) then
Dim tmpsize:tmpsize = CDBL (FormatNumber (CCur (datalength (i))/1024, 2))
If tmpsize <= FileSize Then
Oboolean = Oboolean and True
Else
Serrors = serrors & "Form [" & ItemName (i) & "] File Size (" & Tmpsize & "KB) out of range! \ n "& _
"Support size Range: <=" & fileSize & "kb\n\n"
Oboolean = Oboolean and False
End If
End If
Next
End If
Checksize = Oboolean
End Function

Private Function CreateFolder (ByVal sline, ByVal spath)
Dim oFSO
Set oFSO = Server.CreateObject ("Scripting.FileSystemObject")
If not ofso.folderexists (spath) Then
Dim regEx
Set regEx = New RegExp
Regex.pattern = "^ (. *) \ \ ([^\\]*) $"
Regex.global = False
Regex.ignorecase = True
sline = sline & Regex.Replace (spath, "$") & "|"
spath = Regex.Replace (spath, "$")
If CreateFolder (sline, spath) then CreateFolder = True
Set regEx = Nothing
Else
If sline = "|" Then
CreateFolder = True
Else
Dim stemp:stemp = Mid (sline, 2, Len (sline)-2)
If InStrRev (stemp, "|") = 0 Then
sline = "|"
spath = spath & "\" & Stemp
Else
Dim Folder:folder = Mid (Stemp, InStrRev (stemp, "|") + 1)
sline = "|" & Mid (Stemp, 1, InStrRev (stemp, "|")-1) & "|"
spath = spath & "\" & Folder
End If
Ofso.createfolder spath
If CreateFolder (sline, spath) then CreateFolder = True
End if
End If
Set oFSO = Nothing
End Function

Private Function ParentFolder (ByVal spath)
Dim regEx
Set regEx = New RegExp
Regex.pattern = "^ (. *) \\[^\\]*$"
Regex.global = True
Regex.ignorecase = True
ParentFolder = Regex.Replace (spath, "$")
Set regEx = Nothing
End Function

Private Function isnothing (ByVal sVar)
IsNothing = CBool (SVar = Empty)
End Function

Private Function strpadleft (byVal stext, ByVal slen, ByVal Schar)
Dim stemp:stemp = stext
Do While Len (stemp) < Slen:stemp = Schar & Stemp:loop
Strpadleft = stemp
End Function

Private Function strtobyte (ByVal stext)
For i = 1 to Len (stext)
Strtobyte = strtobyte & ChrB (ASC (Mid (Stext, I, 1))
Next
End Function

Private Function bytetostr (ByVal sByte)
Dim OStream
Set OStream = Server.CreateObject ("ADODB. Stream ")
Ostream.type = 2
Ostream.mode = 3
Ostream.open
Ostream.writetext SByte
ostream.position = 0
Ostream.charset = "gb2312"
Ostream.position = 2
Bytetostr = Ostream.readtext
Ostream.close
Set OStream = Nothing
End Function

Private Function getclientipaddr
If IsNothing (Getservervar ("Http_x_forwarded_for")) Then
GETCLIENTIPADDR = Getservervar ("REMOTE_ADDR")
Else
GETCLIENTIPADDR = Getservervar ("Http_x_forwarded_for")
End If
End Function

Private Function Getservervar (ByVal stext)
Getservervar = Request.ServerVariables (stext)
End Function

Private Function iptonum (ByVal sIp)
Dim sip_1, sip_2, Sip_3, Sip_4
If IsNumeric (Left (sIp, 2) and then
Sip_1 = Left (sip, InStr (SIP, ".")-1)
SIP = Mid (sip, INSTR (SIP, ".") + 1)
Sip_2 = Left (sip, InStr (SIP, ".")-1)
SIP = Mid (sip, INSTR (SIP, ".") + 1)
Sip_3 = Left (sip, InStr (SIP, ".")-1)
Sip_4 = Mid (SIP, INSTR (SIP, ".") + 1)
End If
Iptonum = CInt (sip_1) * * * * * * * * * * * * * * * * + CInt (sip_2) * * * * + CInt (sip_3) * + CInt (sip_4)-1
End Function

REM class-terminate

Private Sub Class_Terminate
Call Delprogress
Form.removeall
Set Form = Nothing
End Sub

End Class
%>

http://www.bkjia.com/PHPjc/323001.html www.bkjia.com true http://www.bkjia.com/PHPjc/323001.html techarticle However, some cases only need to pass several files, and the file volume is not too large, in this case the use of components is a bit sledgehammer to kill the chicken feeling, through the HTML comes with the input type= "file" form ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.