Complete example of uploading cvs files using php

Source: Internet
Author: User
Tags current time json php code trim unique id

Html code:

The code is as follows: Copy code

<Form action = "/message/index/csv" encType = "multipart/form-data" method = "post" target = "uploadcvs">
<Div> <input type = "file" name = "csvfile"/> & nbsp; <input type = "submit" value = "upload"> </div>
<Div id = "upload_info" style = "width: 100%; border: 1px solid #809db9; display: none"> </div>
</Form>

Target = "uploadcvs". It is difficult to debug the code when adding the target. We recommend that you remove this line of code when debugging.

Php code:

The code is as follows: Copy code

Public function csvAction (){
// Get the Upload file name $ fileinfo, including the extension of the file
$ Fileinfo = pathinfo ($ _ FILES ['svfile'] ['name']);
// Determine whether the file extension is csv.
If (! In_array (strtolower ($ fileinfo ['extension']), array ('csv '))){
$ Feed = array ('status' => 'text ');
// Determine the file size
} Else if ($ _ FILES ['csvfile'] ['size']> 1*1024*1024 ){
$ Feed = array ('status' => 'size ');
} Else {
// Successful hours
$ Succdata = array ();
// Error hour group
$ Errdata = array ();
// Count, calculate the number of rows
$ Count = 0;
// Open a temporary file in read-only mode
$ Handle = fopen ($ _ FILES ['svfile'] ['tmp _ name'], "r ");

// Obtain the username information in the database
$ UserMongo = new Application_Model_DbTable_MongoUsers ();
$ DbUsers = $ userMongo-> findAll (array (), array ('login. Username' => true ));
// Write the username information of the user into $ users
$ Users = array ();
Foreach ($ dbUsers as $ user ){
If (isset ($ user ['login'] ['username'])
$ Users [] = $ user ['login'] ['username'];
        }
// Read the csv file information fgetcsv and fgetcsv ($ handle) row by row)
While ($ row = fgetcsv ($ handle )){
// Read the count of a row, so that you can know the number of rows read.
$ Count ++;
Foreach ($ users as $ user ){
// Determine if $ row [0] is the mobile phone number & $ row [0] is equal to $ user, that is, whether this record exists in $ users.
// Write this mobile phone number into the array $ succdata
If (preg_match ('/^ 1 (3 | 4 | 5 | 8) d {9} $/', $ row [0]) & $ user = $ row [0]) {
$ Succdata [$ row [0] = (string) $ row [0];
Break;
                }
            }
// Determine whether $ succdata [$ row [0] exists and $ errdata is not written.
If (! Isset ($ succdata [$ row [0]) {
$ Errdata [$ row [0] = $ row [0];
            }
        }
// Close the file
Fclose ($ handle );
// Save the uploaded cvs file to your project
$ Url = $ this-> _ helper-> Upload-> msgcsv ($ _ FILES ['csvfile'], $ succdata, $ errdata );
// $ Count indicates the number of rows in the csv file, the number of successful rows, and the number of failed rows.
$ Count = array ('original' => $ count, 'success' => count ($ succdata), 'error' => count ($ errdata ));
// $ Feed. The status here is successful, count, and url.
// Count is used to check whether a failed file exists. The url is used to view the list of failed files (because three files are returned during the upload and the failed files are viewed)
$ Feed = array ('status' => 'succ', 'count' => $ count, 'URL' => $ url );
    }
// Json Array json_encode () json encoding
$ Feed = json_encode ($ feed );
// Callback () function <script> parent. callback (". $ feed.") </script>
Echo "<script> parent. callback (". $ feed. ") </script> ";
Exit;
 }

Js code:

The code is as follows: Copy code

// Data is ". $ feed ."
Function callback (data ){
Try {
If (data. status = 'ext '){
Alert ('file type incorrect ');
Return false;
} Else if (data. status = 'size '){
Alert ('file cannot exceed 1 Ms ');
Return false;
} Else if (data. status = 'succ '){
// ParseInt converts a string to an integer parseInt.
Var html = parseInt (data. count. error)> 0? '<A href = "<? Php echo UPLOAD_IMAGE_PATH;?> '+ Data. url. error +' "> View the failure list </a> ':'';
// Number of successful items and number of failed items
Certificate ('upload upload_info'detail .html ('Imported successfully: '+ data. count. success +'; failed: '+ data. count. error + html );
$ ('# Upload_info'). show ();
$ ('Input [name = step3_hidden] '). val (data. url. success );
         }      
} Catch (e ){
Alert ('Resolution error, please check the file format .');
    }
Return false;
}

Upload. Php file

The code is as follows: Copy code

<? Php
// Upload processing
Class Ata_Controller_Action_Helper_Upload extends Zend_Controller_Action_Helper_Abstract {

// Notification csv file
Public function MsgCsv (& $ source, $ succdata, $ errdata ){

// Original cvs retained
// File storage directory
$ PublicPath = realpath (APPLICATION_PATH. "/../public/upload ").'/';
$ CsvPath = "msgcsv/". date ('Y'). '/'. date ('M ')."/";
$ Path = $ publicPath. $ csvPath;
// Create a directory
$ This-> mkdirs ($ path );
// The uniqid () function generates a unique ID based on the current time in microseconds. Uniqid ()
$ Filename = uniqid ();
// Obtain the file extension
$ Ext = pathinfo ($ source ['name'], PATHINFO_EXTENSION );
// Create an empty file, directory, file name, and extension
$ Filepath = $ path. $ filename. '_ org.'. $ ext;
// Move_uploaded_file () to move the uploaded file to the new location
Move_uploaded_file ($ source ['tmp _ name'], $ filepath );

// Create a correct csv file
$ Content = '';
// Create an empty file, directory, file name, and extension
$ Succfile = $ path. $ filename. '_ succ.'. $ ext;
// Write $ succdata into $ content;
Foreach ($ succdata as $ row ){
// The connection string is equivalent to $ content = $ content. $ row. "n"
$ Content. = $ row. "n ";
        }
$ Content = trim ($ content, "n ");
// File_put_contents (), write a string to the file
File_put_contents ($ succfile, $ content );

// Error csv creation
$ Content = '';
$ Errfile = $ path. $ filename. '_ err.'. $ ext;
Foreach ($ errdata as $ row ){
$ Content. = $ row. "n ";
        }
$ Content = trim ($ content, "n ");
File_put_contents ($ errfile, $ content );

// Return three objects (used to view the failure list and write the successful list content to the hidden domain and pass it to the database)
Return array (
'Orginal' => $ csvPath. $ filename. '_ org.'. $ ext,
'Success' => $ csvPath. $ filename. '_ succ.'. $ ext,
'Error' => $ csvPath. $ filename. '_ err.'. $ ext
);
    }
// Delete an object
// Obtain the prefix name of the csv file
Public function rmMsgCsv ($ path ){
// $ Prefix: Get the prefix name of the csv file
$ Prefix = str_replace('_succ.csv ', '', $ path );
// Delete three objects
Unlink(your prefix.'_org.csv ');
Unlink(your prefix.'_succ.csv ');
Unlink(your prefix.'_err.csv ');
    }

Public function mkdirs ($ dir, $ mode = 0777 ){
Return is_dir ($ dir) or ($ this-> mkdirs (dirname ($ dir) and mkdir ($ dir, $ mode ));
    }
}

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.