16/8/14

Mutiple File Upload với php và mysql


Trong hướng dẫn này mình sẽ hướng dẫn upload nhiều tập tin bằng PHP kiểm tra phần mở rộng tập tin và kích thước, để thực hiện một tải lên an toàn và lưu các thông tin tập tin vào một cơ sở dữ liệu MySQL. Sẽ tự tạo folder mới để lưu giữ file. Bắt đầu nhé.


Download Source

1. Database 
CREATE TABLE IF NOT EXISTS `wtt_images` (
  `u_id` int(11) NOT NULL,
  `i_id` int(11) NOT NULL AUTO_INCREMENT,
  `i_filename` varchar(255) NOT NULL,
  `i_filesize` varchar(255) NOT NULL,
  `i_filetype` varchar(20) NOT NULL,
  PRIMARY KEY (`i_id`),
  KEY `u_id` (`u_id`),
  KEY `i_filename` (`i_filename`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

2. db.php Kết nối cơ sở dữ liệu
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'tips_webtricktips');
define('TABLE_PREFIX', 'wtt_');
$db = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
date_default_timezone_set('asia/ho_chi_minh');
3. Html upload mutiple files.

Mutiple upload với php và mysql

4. Upload mutiple file 
 - Kiểm trả dữ liệu upload và tạo folder upload nếu folder đó chưa tồn tại.
     + Kiểm tra dữ liệu upload lên
$fileName = $_FILES['files']['name'][$key];
          $fileSize = $_FILES['files']['size'][$key];
          $fileTmp  = $_FILES['files']['tmp_name'][$key];
          $fileType = $_FILES['files']['type'][$key];  
          //check file size
          if ($fileSize > 2097152) {
              $errors[] = 'Kích thước tập tin lớn hơn 2mb';
          }

          //check file type
          $sourceExt = strtoupper(substr(strrchr($fileName, '.'), 1));

          if (!in_array($sourceExt, array('JPG', 'JPGE', 'PNG', 'GIF'))) {
              $errors[] = 'Vui lòng upload tập tin với các định dạng sau jpg, jpeg, png, gif';
          }

          //check file before process
          if (file_exists('uploads/images/') && !is_writable('uploads/images/')) {
              $errors[] = 'Không có quyền ghi tập tin';
          }
+ Tạo thư mục chứa file nếu chưa tồn tại thư mục
$newName = $fileName; // Ở đây bạn có thể thay đổi tên của file bạn upload lên
              //tien hanh xu ly file se upload
              $name=preg_replace("/[^a-zA-Z0-9_.]/ms", "-", $newName);

              //Lấy tên file và extpart
              $pos = strrpos($name, '.');
              if ($pos === false) {
                  $pos = strlen($name);
              }
              $namePart = substr($name, 0, $pos);
              $extPart = substr(strrchr($name, '.'), 1);

// Tên file mới để trách trùng file thì có thể nối time()
              $finalName = $namePart.'-'.time().".".$extPart;
              $destinationPath = 'uploads/images/'.$namePart.".".$extPart;

              //Tạo destination dir nếu không tồn tại
              if (!file_exists('uploads/images/')) {
                  mkdir('uploads/images/', 0777, true);
              }
- move_uploaded_file 
Bạn có thể nhận được các tập tin sang một vị trí khác bằng cách sử dụng move_uploaded_file(), ở đây mình sẽ di chuyển nó đến một thư mục hình ảnh, và chắc chắn rằng thư mục upload đó tồn tại, kể từ khi move_uploaded_file() không thể tạo một thư mục.
if (!move_uploaded_file($fileTmp, $destinationPath)) {
   $errors[] = 'Lỗi khi upload files';
}
- sql insert xuống CSDL
$sql = "INSERT INTO ".TABLE_PREFIX. "images(
                    u_id,
                    i_filename,
                    i_filesize,
                    i_filetype
                ) VALUES (
                    1,
                    '$fileName',
                    '$fileSize',
                    '$fileType'
                )";
                //insert to sql
                if($db->query($sql)){
                  //Dothing
                }
5 . Toàn bộ phần upload file
include "db.php";

  if (isset($_POST['fsubmit'])) {
        $errors= array();
        foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
          $fileName = $_FILES['files']['name'][$key];
          $fileSize = $_FILES['files']['size'][$key];
          $fileTmp  = $_FILES['files']['tmp_name'][$key];
          $fileType = $_FILES['files']['type'][$key];  
          //check file size
          if ($fileSize > 2097152) {
              $errors[] = 'Kích thước tập tin lớn hơn 2mb';
          }

          //check file type
          $sourceExt = strtoupper(substr(strrchr($fileName, '.'), 1));

          if (!in_array($sourceExt, array('JPG', 'JPGE', 'PNG', 'GIF'))) {
              $errors[] = 'Vui lòng upload tập tin với các định dạng sau jpg, jpeg, png, gif';
          }

          //check file before process
          if (file_exists('uploads/images/') && !is_writable('uploads/images/')) {
              $errors[] = 'Không có quyền ghi tập tin';
          }
          if (count($errors) == 0) {
              $newName = $fileName;
              //tien hanh xu ly file se upload
              //$name=ereg_replace("[^a-zA-Z0-9_.]","-", $newName);
              $name=preg_replace("/[^a-zA-Z0-9_.]/ms", "-", $newName);

              //find namepart and extension part
              $pos = strrpos($name, '.');
              if ($pos === false) {
                  $pos = strlen($name);
              }
              $namePart = substr($name, 0, $pos);
              $extPart = substr(strrchr($name, '.'), 1);

              $finalName = $namePart.'-'.time().".".$extPart;
              $destinationPath = 'uploads/images/'.$namePart.".".$extPart;

              //create destination directory if not exists
              if (!file_exists('uploads/images/')) {
                  mkdir('uploads/images/', 0777, true);
              }

              if (!move_uploaded_file($fileTmp, $destinationPath)) {
                  $errors[] = 'Lỗi khi upload files';
              } else {
                $success = 1;

                $sql = "INSERT INTO ".TABLE_PREFIX. "images(
                    u_id,
                    i_filename,
                    i_filesize,
                    i_filetype
                ) VALUES (
                    1,
                    '$fileName',
                    '$fileSize',
                    '$fileType'
                )";
                //insert to sql
                if($db->query($sql)){
                  //Dothing
                }
              }
          }
      }
      if(empty($errors)) {
        echo 'Upload files thành công';
      }
    }
6. Hy vọng bài viết sẽ có ích cho các bạn. Bài tới mình sẽ viết về Mutiple File Upload với php, jquery ajax và mysql để có thể hiển thị thấy ngay hình ảnh sau khi upload thành công.
webtricktips - Chúc vui vẽ

Không có nhận xét nào:

Đăng nhận xét