Codeigniter上传excel并保存到数据库(网络错误(tcp_error))

时间:2017-06-05 10:37:24

标签: php excel codeigniter codeigniter-3

真的需要你的支持。 在我们决定将其上传到公开之前,这在Intranet上有效。

我正在使用Codeigniter + SQL Server + Apache

这应该如何运作: 上传excel文件,阅读内容,保存到数据库并发送电子邮件&短信。

但: 每次我在3分钟后上传excel文件时它会停止并在Developer Opt-> Network Tab上写下这个错误: “网络错误(tcp_error) 发生通信错误:“” Web服务器可能已关闭,太忙或遇到阻止其响应请求的其他问题。您可能希望稍后再试。“ enter image description here

这是我的代码:

    public function do_upload()
    {
        set_time_limit(0);
        ignore_user_abort(1);
        $accID = $this->input->get('acc');
        $rmi = $this->input->get('rmi');
        $spInst = $this->input->get('spInst');
        $dateReq = '';
        $dateReqq = $this->input->get('dateReq');
        if($dateReqq==null or $dateReqq==''){
            $dateReq = date('Y-m-d');
        }else{
            $dateReq = $this->input->get('dateReq');
        }

        $dateNow = date("F_d_Y__h_i_s__A");
        $status = "";
        $msg = "";
        $file_element_name = 'file';
         $file_name = '';
        if ($status != "error")
        {
            $config['upload_path'] = 'c:/xampp/htdocs/eDR/assets/uploads/';
            $config['allowed_types'] = 'xlsx';
            $config['max_size'] = 60000;
            $config['overwrite']            = TRUE;
            $config['remove_spaces']        = TRUE;
            $config['file_name']            = uniqid('file')."_". $dateNow;
            $this->load->library('upload', $config);

            if (!$this->upload->do_upload($file_element_name))
            {
                $status = FALSE;
                $msg = $this->upload->display_errors('', '');
            }
            else
            {
                $data = $this->upload->data();
                //$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
                //if($file_id)
                //{
                $file_name = $data['file_name'];
                $file = "c:/xampp/htdocs/eDR/assets/uploads/" . $file_name;
                $this->do_read($file,$accID,$rmi,$spInst,$dateReq);
                $status = TRUE;
                $msg = "File successfully uploaded";
                //}
                //else
               // {
                 //   unlink($data['full_path']);
                  //  $status = "error";
                   // $msg = "Something went wrong when saving the file, please try again.";
               // }
            }
            @unlink($_FILES[$file_element_name]);
        }




      echo json_encode(array('status' => $status, 'msg' => $msg, 'name' => $file_name));
    }


    public function do_read($file,$accID,$rmi,$spInst,$dateReq){
        //load the excel library
        $this->load->library('excel');
        //read file from path
        $objPHPExcel = PHPExcel_IOFactory::load($file);
        //get only the Cell Collection
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
        //extract to a PHP readable array format
        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            //header will/should be in row 1 only. of course this can be modified to suit your need.
            //if ($row == 1) {
              //  $header[$row][$column] = $data_value;
            //} else {
                $arr_data[$row][$column] = $data_value;
            //}
        }
        //send the data in an array format
        //$data['header'] = $header;
        $drCount = ($this->up->get_DRcount($accID));
        $date = date("F d, Y  h:i: s A");
        $data['values'] = $arr_data;
        $last = count($arr_data) - 1;
        $totalQty = 0;
        $abbr = $this->up->get_Abbr($accID);
        $TATnAGING = '';
        $dAdd ='';
        $posReq='';
        $reqD;
        foreach ($arr_data as $i => $row)
        {
            if(     empty($row['B']) or
                    empty($row['C']) or
                    empty($row['D']) or
                    empty($row['E']) or
                    empty($row['F']) or
                    empty($row['G']) or
                    empty($row['H']) or
                    empty($row['I']) or
                    empty($row['J']) or
                    empty($row['K'])
            ){
                    $msg = 'B = ' . $row['B'] . ' C = ' . $row['C'] . ' D = ' . $row['D'] . ' E = ' . $row['E'] . ' F = ' . $row['F'] . ' G = ' . $row['G'] . ' H = ' . $row['H'] . ' I = ' . $row['I'] 
                            . ' J = ' . $row['J'] . ' K = ' . $row['K']  ;
                 $status = FALSE;
                 echo json_encode(array('status' => $status, 'msg'=>$msg));
                 exit();
            }
        }
        foreach ($arr_data as $i => $row)
        {

            try {
            $reqDatee        = date('F d, Y', strtotime($dateReq));
            $start = new DateTime( $reqDatee );
            $end = new DateTime(date("F d, Y"));
            $oneday = new DateInterval("P1D");
            $days = array();
            $data1 = "7.5";
            foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
                $day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
                if($day_num < 6) { /* weekday */
                    $days[$day->format("Y-m-d")] = $data1;
                } 
            }               

            $TATnAGING   = count($days). ' day/s';

            $dAdd = trim(strtoupper($row['D']));
            $posReq = trim(strtoupper($row['B']));
            $reqD = $dateReq;
            $isFirst = ($i == 0);
            $isLast = ($i == $last);
            $id = $this->session->userdata('username');
            $totalQty += $row['G'];
            } catch (Exception $e) {
                    $msg = 'Caught exception: '.  $e->getMessage(). "\n";
                    $status = FALSE;
                    echo json_encode(array('status' => $status, 'error'=>$msg));
                    exit();
            }
            if($i>1){
                $data1 = array();

            try {

            if(trim(strtoupper($row['B']))=='YES' or trim(strtoupper($row['B']))=='Y'){
                $data1 = array(
                    "drRef"             =>      $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
                    "postReq"           =>      trim(strtoupper($row['B'])),
                    "reqDate"           =>      $dateReq,
                    "reqBy"             =>      trim(strtoupper($row['C'])),
                    "deliveryAcc"       =>      trim(strtoupper($row['D'])),
                    "matCode"           =>      trim(strtoupper($row['E'])),
                    "matDescription"    =>      trim(strtoupper($row['F'])),
                    "qty"               =>      $row['G'],
                    "UOM"               =>      trim(strtoupper($row['H'])),
                    "location"          =>      trim(strtoupper($row['I'])),
                    "postRef"           =>      '',
        //          "postDate"          =>      date("F d, Y h:i:s A"),
        //          "postBy"            =>      $this->session->userdata['name'],
                    "status"            =>      'PENDING FOR POSTING',
        //          "TAT"               =>      trim(strtoupper($row['O'])),
        //          "AGING"             =>      trim(strtoupper($row['P'])),
                    "userID"            =>      $id,
                    'addedBy'           =>      $this->session->userdata('name'),
                    'addedUsing'        =>      gethostbyaddr($_SERVER['REMOTE_ADDR']),
                    'dateAdded'         =>      $date,
                    'seqNo'             =>      uniqid(),
                    'accID'             =>      $accID,
                    'fromIMEI'          =>      trim(strtoupper($row['J'])),
                    'toIMEI'            =>      trim(strtoupper($row['K'])),
                    );  
                }else{
                    $data1 = array(
                    "drRef"             =>      $abbr .'2017' . sprintf("%07d", ($drCount + 1)),
                    "postReq"           =>      trim(strtoupper($row['B'])),
                    "reqDate"           =>      $dateReq,
                    "reqBy"             =>      trim(strtoupper($row['C'])),
                    "deliveryAcc"       =>      trim(strtoupper($row['D'])),
                    "matCode"           =>      trim(strtoupper($row['E'])),
                    "matDescription"    =>      trim(strtoupper($row['F'])),
                    "qty"               =>      $row['G'],
                    "UOM"               =>      trim(strtoupper($row['H'])),
                    "location"          =>      trim(strtoupper($row['I'])),
                    "postRef"           =>      '',
                    "postDate"          =>      date("F d, Y h:i:s A"),
                    "postBy"            =>      $this->session->userdata['name'],
                    "status"            =>      'POSTED',
                    "TAT"               =>      $TATnAGING,
                    "userID"            =>      $id,
                    'addedBy'           =>      $this->session->userdata('name'),
                    'addedUsing'        =>      gethostbyaddr($_SERVER['REMOTE_ADDR']),
                    'dateAdded'         =>      $date,
                    'seqNo'             =>      uniqid(),
                    'accID'             =>      $accID,
                    'fromIMEI'          =>      trim(strtoupper($row['J'])),
                    'toIMEI'            =>      trim(strtoupper($row['K'])),
                    );  
            }

                } catch (Exception $e) {
                   $msg = 'Caught exception: '.  $e->getMessage(). "\n";
                    $status = FALSE;
                    echo json_encode(array('status' => $status, 'error'=>$msg));
                    exit;
                }
            $insert = $this->up->save($data1);
            $data1 = array();
            }
        }
        if($posReq=='YES' or $posReq=='Y'){
                $data1 = array(
                    'drRef' => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
                    'accID' => $accID,
                    'userID' => $this->session->userdata['id'],
                //    'postRef' => trim(strtoupper($row['K'])),
                //    'postBy' => $this->session->userdata['name'],
                //    'postDate' => $date,
                    'totQty' => $totalQty,
                    'status' => 'PENDING FOR POSTING',
                    'isPosted' => 'No',
                    'isApproved' => 'Pending',
                    'approverID' => $this->session->userdata('head'),
                    'postReq' => $posReq,
                    'reqDate' => $reqD,
                    'deliveryAdd' => $dAdd,
                    'reason'    => urldecode($rmi),
                    'spInst'    => urldecode($spInst),
                );
            }else{
                $data1 = array(
                    'drRef' => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
                    'accID' => $accID,
                    'userID' => $this->session->userdata['id'],
                    //'postRef' => $this->session->userdata('username'),
                    'postBy' => $this->session->userdata['name'],
                    'postDate' => $date,
                    'totQty' => $totalQty,
                    'status' => 'POSTED',
                    'isPosted' => 'Yes',
                    'isApproved' => 'Pending',
                    'approverID' => $this->session->userdata('head'),
                    'postReq' => $posReq,
                    'tat' => $TATnAGING  ,
                    'reqDate' => $reqD,
                    'deliveryAdd' => $dAdd,
                    'reason'    => urldecode($rmi),
                    'spInst'    =>  urldecode($spInst),
                );
            }

        $insert = $this->up->saveOrder($data1);

        $drRef = $abbr . '2017' . sprintf("%07d", ($drCount + 1));

        $id = $this->up->get_Data('head','tblUser','userID',$this->session->userdata('id'));
        $recepient = $this->up->get_Data('email','tblUser','userID',$id);
        $name = $this->up->get_Data('name','tblUser','userID',$id);

        $config = Array(
             'protocol' => 'smtp',
             'smtp_host' => '182.50.151.61',
             'smtp_port' => 587,
             'smtp_user' => 'user',
             'smtp_pass' => 'pass',
             'mailtype'  => 'html',
             'charset'   => 'iso-8859-1'
             );
             $this->load->library('email', $config);
             $this->email->set_newline("\r\n");
            // Set to, from, message, etc.
         $this->email->from('eDR@domain.com', 'e - Delivery Receipt'); 
         $this->email->to($recepient);
         //$this->email->subject('eDR Notifications');
         $this->email->subject('eDR Notification < DR Request >');
         $message = 'Message';
         $this->email->message($message);
         $result = $this->email->send();
         // if (!$result) { 
             // $this->email->print_debugger();
         // }

        $receiver = $this->up->get_Data('phoneNum','tblUser','userID',$this->session->userdata('head'));
        $sms = array(
            'receiver'  =>  $receiver,
            'msg'       =>  'message',
            'status'    =>  'Send',
        );
        $this->up->sendSMS($sms);
}

感谢。

1 个答案:

答案 0 :(得分:0)

我通过CRON作业或在我的PHP脚本上调用cmd命令解决了这个问题,这样它就可以非常快速地在服务器上执行查询。 :)