Php program code for file Upload

Source: Internet
Author: User
Tags file upload temporary file storage

First look at the instance

The code is as follows: Copy code

<? Php
      
// Determine whether the temporary file storage path contains the file uploaded by the user
If (is_uploaded_file ($ _ FILES ["uploadfile"] ["tmp_name"]) {
// Store information in variables for higher efficiency
$ Upfile = $ _ FILES ["uploadfile"]; // use an array string to store the information of the uploaded file.
// Print_r ($ upfile ); // if printed, the output is similar to this information Array ([name] => m.jpg [type] => image/jpeg [tmp_name] => C: WINDOWSTempphp1A. tmp [error] = & gt; 0 [size] = & gt; 44905)
$ Name = $ upfile ["name"]; // This parameter can be used to transfer files later.
$ Type = $ upfile ["type"]; // file Upload type
$ Size = $ upfile ["size"]; // size of the uploaded file
$ Tmp_name = $ upfile ["tmp_name"]; // temporary name of the file uploaded by the user
$ Error = $ upfile ["error"]; // error message during Upload
// Echo $ name;
// Determine the file type to determine whether to transfer the file. If yes, set $ OK = 1 to transfer the file.
Switch ($ type ){
Case "image/jpg": $ OK = 1;
Break;
Case "image/jpeg": $ OK = 1;
Break;
Case "image/gif": $ OK = 1;
Break;
Default: $ OK = 0;
Break;
        }
// If the file meets the requirements and there is no error during the upload process
If ($ OK & $ error = '0 '){
// Call the move_uploaded_file () function for file transfer
Move_uploaded_file ($ tmp_name, 'up/'. $ name );
// After the operation is successful, a message is displayed, indicating that the operation is successful.
Echo "<script language =" javascript "> alert ('sudoed') </script> ";
} Else {
// If the file does not match the type or the upload process has an error, the system prompts "failed".
Echo "<script language =" javascript "> alert ('failed') </script> ";
        }
    }
?>
<! -- Set the file submission form -->
<Form enctype = "multipart/form-data" method = "post" name = "uploadform">
<Input type = "file" name = "uploadfile" value = "Upload File">
<Input type = "submit" name = "submit" value = "Upload">
</Form>

The above code can work completely, but it is a lot of loopholes in the actual application, let's gradually improve first, the uploaded file must have a fixed directory to save, here we use a $ UploadPath variable to save it, for example, $ UploadPath = "/home/flier/upload /";
Or more complex automatic positioning, such

The code is as follows: Copy code
$ UploadPath = AddSlashes (dirname ($ PATH_TRANSLATED). "\ upload \";

$ PATH_TRANSLATED is the current transfer directory.
Assume that the uploaded file is saved in a subdirectory named upload. The dirname function returns the directory name, adds the subdirectory name, and saves the complete uploaded file name and path with the variable $ FileName.

$ FileName = $ UploadPath. $ UploadFile_name;
Secondly, we also want users to learn brief information about the uploaded file, such as the size of the uploaded file if ($ UploadFile_size <1024) {// The size of the uploaded file
   

The code is as follows: Copy code
$ FileSize = (string) $ UploadFile_size. "byte ";
}
Elseif ($ UploadFile_size <(1024*1024 )){
$ FileSize = number_format (double) ($ UploadFile_size/1024), 1). "KB ";
}
Else {
$ FileSize = number_format (double) ($ UploadFile_size/(1024*1024), 1). "MB ";
}  

The number_format function is used to format the output. For detailed usage, see the manual. Next, we must take into account the existence of the file and the copy operation failure, and provide the corresponding prompt information if (! File_exists ($ FileName )){
 

The code is as follows: Copy code
If (copy ($ UploadFile, $ FileName )){
Echo "file $ UploadFile_name ($ FileSize) uploaded successfully! ";
     }
Else {
Echo "file $ UploadFile_name Upload failed! ";
     }
Unlink ($ UploadFile );
}
Else {
Echo "file $ UploadFile_name already exists! ";
}

Then we should take into account that the upload of large files is prone to timeout, you can use set_time_limit ($ TimeLimit); increase the timeout limit.

Finally, the section and implementation code are integrated into a separate file. To achieve this idea, we add an implicit VALUE <input type = "hidden" NAME = "UploadAction" VALUE = "1"> in form to indicate the current status (interface or implementation), so that we can treat it differently.

The following program can be used for instance applications

The code is as follows: Copy code

Function FileUpload ($ resourceType, $ currentFolder, $ sCommand)
{
If (! Isset ($ _ FILES )){
Global $ _ FILES;
 }
$ SErrorNumber = '0 ';
$ SFileName = '';

If (isset ($ _ FILES ['newfile']) &! Is_null ($ _ FILES ['newfile'] ['tmp _ name'])
 {
Global $ Config;

$ OFile = $ _ FILES ['newfile'];

// Map the virtual path to the local server path.
$ SServerDir = ServerMapFolder ($ resourceType, $ currentFolder, $ sCommand );

// Get the uploaded file name.
$ SFileName = $ oFile ['name'];
$ SFileName = SanitizeFileName ($ sFileName );

$ SOriginalFileName = $ sFileName;

// Get the extension.
$ SExtension = substr ($ sFileName, (strrpos ($ sFileName, '.') + 1 ));
$ SExtension = strtolower ($ sExtension );

If (isset ($ Config ['secureimageupload'])
  {
If ($ isImageValid = IsImageValid ($ oFile ['tmp _ name'], $ sExtension) === false)
   {
$ SErrorNumber = '123 ';
   }
  }

If (isset ($ Config ['htmlextension'])
  {
If (! IsHtmlExtension ($ sExtension, $ Config ['htmlextension']) &
($ DetectHtml = DetectHtml ($ oFile ['tmp _ name']) = true)
   {
$ SErrorNumber = '123 ';
   }
  }

// Check if it is an allowed extension.
If (! $ SErrorNumber & IsAllowedExt ($ sExtension, $ resourceType ))
  {
$ ICounter = 0;

While (true)
   {
$ SFilePath = $ sServerDir. $ sFileName;

If (is_file ($ sFilePath ))
    {
$ ICounter ++;
$ SFileName = RemoveExtension ($ sOriginalFileName). '('. $ iCounter. ').'. $ sExtension;
$ SErrorNumber = '123 ';
    }
Else
    {
Move_uploaded_file ($ oFile ['tmp _ name'], $ sFilePath );

If (is_file ($ sFilePath ))
     {
If (isset ($ Config ['chmodonupload']) &! $ Config ['chdonupload'])
      {
Break;
      }

$ Permissions = 0777;

If (isset ($ Config ['chmodonupload']) & $ Config ['chmodonupload'])
      {
$ Permissions = $ Config ['chmodonupload'];
      }

$ Oldumask = umask (0 );
Chmod ($ sFilePath, $ permissions );
Umask ($ oldumask );
     }

Break;
    }
   }

If (file_exists ($ sFilePath ))
   {
// Previous checks failed, try once again
If (isset ($ isImageValid) & $ isImageValid ===- 1 & IsImageValid ($ sFilePath, $ sExtension) === false)
    {
@ Unlink ($ sFilePath );
$ SErrorNumber = '123 ';
    }
Else if (isset ($ detectHtml) & $ detectHtml ===- 1 & DetectHtml ($ sFilePath) === true)
    {
@ Unlink ($ sFilePath );
$ SErrorNumber = '123 ';
    }
   }
  }
Else
$ SErrorNumber = '123 ';
 }
Else
$ SErrorNumber = '123 ';


$ SFileUrl = CombinePaths (GetResourceTypePath ($ resourceType, $ sCommand), $ currentFolder );
$ SFileUrl = CombinePaths ($ sFileUrl, $ sFileName );

SendUploadResults ($ sErrorNumber, $ sFileUrl, $ sFileName );

Exit;

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.