Php _ PHP Tutorial

Source: Internet
Author: User
Php to deal with the multifile Upload of common forms. However, in some cases, only a few files need to be passed, and the file size is not too large. in this case, using components is a bit cool, you can use the inputtypefile form that comes with html. However, in some cases, you only need to pass a few files, and the file size is not large. in this case, using components is a bit cool. The key to implementing the required functions is the processing of the background receiver.

Php makes it easy to process uploads. The information of uploaded FILES is automatically processed by the server to the $ _ FILES array. developers only need to use the built-in processing functions for simple operations. ASP developers are not so lucky. the official team does not provide direct processing methods. developers need to design their own solutions, in this case, developers need to understand how IIS processes the enctype = "multipart/form-data" form, IIS stores the data submitted by the enctype = "multipart/form-data" form into binary data and returns it to the developer in binary format, the developer needs to analyze the uploaded content through the byte processing functions of LenB and MidB. the specific form data format sent by the client can understand the transmission format of HTTP RFC1867.

The following describes how to upload multiple files, including php and asp.

Php: WEBSITE_DIRROOT indicates the website root directory:

The 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 ('The File for upload is not found! ');
}
}

$ 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 ('upload not allowed '. $ up_file ['type'].' format file! ');

If ($ up_file ['size']/1024> $ this-> up_max ){
Exit ('cannot upload files larger than'. $ this-> up_max. 'K! ');
}
}
} 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 ('upload is not allowed. '. $ up_ext.' format file! ');

If ($ up_file ['size']/1024> $ this-> up_max ){
Exit ('cannot upload files larger than'. $ this-> up_max. 'K! ');
}
}
}

$ This-> Uploading ();
}

Private function Uploading (){
If (IO: DIRCreate ($ 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 not enabled! ');
}
} Else {
Exit ('upload directory creation failed! ');
}
}

Public function GetUpload (){
Return empty ($ this-> up_ret )? False: $ this-> up_ret;
}

Function _ destruct (){}
}
?>


Asp:

The 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 Partition B (iStart, formData, bSeparate) = 0
IStart = Sort B (iStart, formData, bSeparate) + LenB (bSeparate) + 14
ILength = Sort B (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 = Sort B (1, dataPart, ChrB (34) + 1
ILength = Clerk B (iStart, dataPart, ChrB (34)-iStart
ItemName (iCount) = GetItemName (MidB (dataPart, iStart, iLength ))
IStart = Sort B (1, dataPart, bVBCrlf) + 4
ILength = LenB (dataPart)-iStart + 1
If limit B (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, "$1 ")
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, "$1 "))
Set regEx = Nothing
End Function

Private Function GetRandomName (byVal sLen)
Dim regEx, sTemp, arrFields, n: 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 (61 * 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, "$1 ")
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 (34)-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 Not 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 & "form [" & itemName (I) & "] file format error! \ 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 & "form [" & itemName (I) & "] file format error! \ 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
The file size ("& tmpSize &" KB) of sErrors = sErrors & "form [" & itemName (I) & "] is out of the range! \ N "&_
"Supported size range: <=" & fileSize & "KB \ 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, "$2") & "|"
SPath = regEx. Replace (sPath, "$1 ")
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 limit Rev (sTemp, "|") = 0 Then
SLine = "|"
SPath = sPath & "\" & sTemp
Else
Dim Folder: Folder = Mid (sTemp, limit Rev (sTemp, "|") + 1)
SLine = "|" & Mid (sTemp, 1, Rev (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, "$1 ")
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) 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) * 256*256*256 + CInt (sIp_2) * 256*256 + CInt (sIp_3) * 256 + CInt (sIp_4)-1
End Function

Rem class-TERMINATE

Private Sub Class_Terminate
Call DelProgress
Form. RemoveAll
Set Form = Nothing
End Sub

End Class
%>


Encoding 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.