Php uploads and downloads files using native functions

Source: Internet
Author: User
If ($ _ FILES & amp; $ _ FILES [attachment] & amp; $ _ FILES [attachment] [tmp_name]) {$ filesize $ _ FILES [attachment] [size]; file upload:

If ($ _ FILES & $ _ FILES ['attachment'] & $ _ FILES ['attachment'] ['tmp _ name']) {$ filesize = $ _ FILES ['attachment '] ['size']; // File upload size limit: 5 M if ($ filesize> 5*1024*1024) {exit ('the size of the uploaded file exceeds the limit! ');} // File storage directory. if not, create $ uploaddir = ROOT_DIR.'/public/attachment/notice/'. if (! File_exists ($ uploaddir) mkdir ($ uploaddir, 0755, true); // Get the Upload file extension $ arr_file = explode ('. ', basename ($ _ FILES ['attachment'] ['name']); $ filetype = $ arr_file [count ($ arr_file)-1]; // Obtain the source file name $ attachment_name = basename ($ _ FILES ['attachment'] ['name']); // rename the file to avoid the impact of Chinese characters $ fname = md5 (basename ($ _ FILES ['attachment '] ['name']). microtime ()). '. '. $ filetype; $ uploadfile = $ uploaddir. $ fname; if (move_uploaded_f Ile ($ _ FILES ['attachment'] ['tmp _ name'], $ uploadfile )) {// Obtain the relative file path $ attachment = '/public/attachment/notice /'. $ fname;} else {exit ('file Upload failed! ');}}

Note: "attachment" is the name of the uploaded file, which is modified according to the specific attribute values in the project. This upload process does not limit the file type. you can handle it as needed.

File download:

// Enter the file tag Header ("Content-type: application/octet-stream"); Header ("Accept-Ranges: bytes"); Header ("Accept-Length :". filesize ($ attachment_filepath); Header ("Content-Disposition: attachment; filename = ". $ attachment_filename); // output file content // read the file content and directly output it to the browser echo file_get_contents ($ attachment_filepath); exit ();

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.