PHP file upload, download, SQL tool class !,

Source: Internet
Author: User
Tags php file upload

PHP file upload, download, SQL tool class !,

PHP file upload, download, SQL tool class! You can directly use the file size and file type to overwrite Chinese transcoding operations with the same name.

Front-endUpload.html

<! DOCTYPE html> 

 

 

ControllerFileProcess. php

<? Php require_once 'fileservice. php'; $ FileService = new fileService (); if (! Empty ($ _ REQUEST ['flag']) {$ flag =$ _ REQUEST ['flag']; // upload if ($ flag = "upload ") {$ username = $ _ POST ['username']; $ intro =$ _ POST ['intro']; $ fileService-> Upload ($ username, $ intro );} elseif ($ flag = "down") {// receives the name of the object to be downloaded $ filepath =$ _ GET ['filepath']; $ filename = $ _ GET ['filename']; $ fileService = new FileService (); $ fileService-> Download ($ filepath, $ filename) ;}}?>

 

BackgroundFileService. php

 

<? Php header ("content_type: text/html; charset = UTF-8"); require_once 'sqlhelper. php'; error_reporting (E_ALL &~ E_NOTICE); class FileService {// function fileInfo () {$ SQL = "select * from upload"; $ sqlHelper = new SqlHelper (); $ res = $ sqlHelper-> execute_dpl ($ SQL); return $ res; $ res-> free ();} /** File Upload * function * Restrict File Size/type * prevent different users from overwriting images of the same name * prevent the same file name uploaded by the same user * parameter * $ username * $ intro ** is_uploaded_file Upload to tmp cache * move_uploaded_file move to target file */function Upload ($ username, $ intro) {/********** restrict the file type *********** // obtain the file size. The size of the uploaded file is 10 MB. $ file_size = $ _ FILES ['myfile'] ['SIZE']; if ($ file_size> 10*1024*1024) {echo "<script> alert ('upload failed, the file to be uploaded cannot exceed 10m'); history. go (-1); </script> "; // echo" Upload Failed. the uploaded file cannot exceed 10 MB! "; Exit () ;}// restrict the upload file type/* $ file_type =$ _ FILES ['myfile'] ['type']; if ($ file_type! = 'Image/jpg '& $ file_type! = 'Image/pjpeg ') {echo "Upload Failed. The file type can only be jpg! "; Exit ();} * // determines whether the file is successfully uploaded. if (is_uploaded_file ($ _ FILES ['myfile'] ['tmp _ name']) {/*** to prevent different users from uploading images with the same name from being overwritten-> Create a folder for each user ***** // create a folder by id during normal creation (replace username with id, to prevent Chinese characters from garbled characters. // create a corresponding folder for each user dynamically $ user_path = $ _ SERVER ['document _ root']. "Demo/File/UpDown/upload /". $ username; // determine whether the user has a folder if (! File_exists ($ user_path) {mkdir ($ user_path );} /***** prevent the same file name uploaded by the same user from being the same-> Add a timestamp to each file name ******* // the file name in tmp $ file_name = $ _ FILES ['myfile'] ['name']; // transfer the cached file to your desired directory $ uploaded_file = $ _ FILES ['myfile'] ['tmp _ name']; // target Path = (target directory + User Name) + current time + suffix (location where strpos () string first appears) $ move_to_file = $ user_path. "/". time (). rand (1,1000 ). substr ($ file_name, strpos ($ file_name ,". "); // transcode the Chinese path $ move_to_file = iconv (" UTF-8 "," gb2312 ", $ Move_to_file ); ******************* * *** // save it to the database $ uptime = date ('Y-m-d H: i: s'); // get the current upload time $ SQL = "insert into upload (username, fname, fsize, uptime, fpath, intro) values ('$ username ', '$ file_name', '$ file_size', '$ uptime', '$ move_to_file', '$ intro') "; $ sqlHelper = new SqlHelper (); $ res = $ sqlHelper-> execute_dml ($ SQL); // determine whether to move the uploaded file to the target location (first, determine whether the upload is successful, and then determine whether the file is added to the database) if (move_uploaded_file ($ Uploaded_file, $ move_to_file) {// res = 1 indicates that the upload is successfully added if ($ res = 1) {echo "<script> alert ('{$ _ FILES ['myfile'] ['name']} File Uploaded successfully'); window. location. href = 'down. php'; </script> ";}else {echo" <script> alert ('file upload failed'); history. go (-1); </script> ";}} else {echo" <script> alert ('file upload failed'); history. go (-1); </script> ";}} else {echo" <script> alert ('file upload failed'); history. go (-1); </script> ";}}/***** parameter description: * download file ** $ filepath file path * $ Filename file name **/function Download ($ filepath, $ filename) {// transcode the Chinese file name $ filename = iconv ("UTF-8", "GB2312 ", $ filename); if (! File_exists ($ filepath) {// check whether the file contains echo "<script> alert ('this file does not exist! '); History. go (-1); </script> "; // echo" the file does not exist! "; Return ;}$ fp = fopen ($ filepath, 'R'); // open the file $ file_size = filesize ($ filepath ); // calculate the file size if ($ file_size> 10*1024*1024) {echo "<script> window. alert ('file is too large, you do not have permission to download ') </script> "; return;} // HTTP header information header (" Content-type: application/octet-stream "); header (" Accept-Ranges: bytes "); header (" Accept-Length :". $ file_size); header ("Content-Disposition: attachment; filename = ". $ filename); $ buffer = 1024; // Download Security: A file byte reading counter $ file_count = 0; // checks whether the file ends feof while (! Feof ($ fp) & ($ file_size-$ file_count> 0) {$ file_data = fread ($ fp, $ buffer ); // count the number of bytes read $ file_count + = $ buffer; echo "$ file_data"; // send the data to the browser} fclose ($ fp) ;}}?>

 

 

 

 

Tool type: SqlHelper. php

 

<? Php/*** SQL tool class (dml, dpl, dpl_arr, close_link) ** 1. create a MySqli object * 2. operation database (send SQL) * 3. processing result * 4. close resources **/class SqlHelper {private $ link; private static $ host = 'localhost'; private static $ user = 'root'; private static $ pwd = ''; private static $ db = 'test'; public function _ construct () {// initialize $ this-> link = new MYSQLi (self ::$ host, self :: $ user, self ::$ pwd, self ::$ db); if ($ this-> link-> connect_error) {die ("Data Database Connection Failed ". $ this-> link-> connect_error);} $ this-> link-> query ("set names utf8 ");} /*** dpl operation ** @ param unknown $ SQL */public function execute_dpl ($ SQL) {$ res = $ this-> link-> query ($ SQL) or die ("failed to operate dpl ". $ this-> link-> error); return $ res;}/*** dpl operation * @ param $ SQL * @ return arr * put the result in an array. In this way, the resource can be closed at any time, and an array */public function execute_dpl_arr ($ SQL) {$ arr = array () is returned (); $ res = $ this-> link-> query ($ SQL) or die ("Operation dpl_arr failed ". $ this-> link-> error); // set $ res => $ arr, transfer the result set content to an array while ($ row = $ res-> fetch_assoc () {$ arr [] = $ row ;} // The resource can be immediately closed here $ res-> free (); return $ arr ;} /*** update/delete/insert * @ param unknown $ SQL */public function execute_dml ($ SQL) {$ res = $ this-> link-> query ($ SQL) o R die ("failed to operate dml". $ this-> link-> error); if (! $ Res) {return 0; // failure} else {if ($ this-> link-> affected_rows> 0) {return 1; // success} else {return 2; // No rows are affected} $ res-> free ();} // close the public function close_link () {if (! Empty ($ this-> link) {$ this-> link-> close ();}}}

 

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.