Advertisement
Guest User

q8340946.html

a guest
Nov 9th, 2013
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.10 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * 文字コードをUTF-8に変換
  5.  */
  6. function to_utf8($str) {
  7.     return mb_convert_encoding(
  8.         $str,
  9.         'UTF-8',
  10.         'ASCII,JIS,UTF-8,CP51932,SJIS-win'
  11.     );
  12. }
  13.  
  14. /**
  15.  * 例外スタックを古い順にして配列に変換
  16.  */
  17. function exception_to_array($e) {
  18.     do {
  19.         $messages[] = $e->getMessage();
  20.     } while($e = $e->getPrevious());
  21.     return array_reverse($messages);
  22. }
  23.  
  24. /**
  25.  * 例外をスロー
  26.  */
  27. function e($message, $previous = null) {
  28.     throw new RuntimeException(to_utf8($message), 0, $previous);
  29. }
  30.  
  31. // 例外変数初期化
  32. $e = null;
  33.  
  34. if (isset($_FILES['upfile'])) {
  35.    
  36.     try {
  37.        
  38.         /* データベース接続 */
  39.        
  40.         // PDOオブジェクト生成
  41.         $pdo = new PDO(
  42.             'mysql:dbname=shop;host=127.0.0.1;charset=utf8',
  43.             'user',
  44.             'password',
  45.             array(
  46.                 // エラーモードを例外スローに設定
  47.                 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  48.                 // LOAD DATA INFILE する際には character_set_database の適切な指定が必要
  49.                 PDO::MYSQL_ATTR_INIT_COMMAND => 'SET character_set_database=utf8',
  50.             )
  51.         );
  52.         // プリペアドステートメント生成
  53.         $stmt = $pdo->prepare(implode(' ', array(
  54.             'LOAD DATA INFILE ?',
  55.             'INTO TABLE `food`',
  56.             'FIELDS',
  57.             'TERMINATED BY ?',
  58.             'ENCLOSED BY ?',
  59.             'LINES TERMINATED BY ?',
  60.             'IGNORE 1 LINES',
  61.         )));
  62.         // 固定値はすぐバインド
  63.         $stmt->bindValue(2, ',');
  64.         $stmt->bindValue(3, '"');
  65.         $stmt->bindValue(4, "\n");
  66.        
  67.         /* パラメータチェック1 */
  68.         if (!is_array($_FILES['upfile']['error'])) {
  69.             e('パラメータが不正です。', $e);
  70.         }
  71.        
  72.         /* パラメータチェック2 & SQL実行 */
  73.         foreach ($_FILES['upfile']['error'] as $key => $error) {
  74.            
  75.             try {
  76.                
  77.                 if (is_array($error)) {
  78.                     e("[{$key}] パラメータが不正です。", $e);
  79.                 }
  80.                 switch ($error) {
  81.                     case UPLOAD_ERR_OK: // エラーが何もない時
  82.                         break;
  83.                     case UPLOAD_ERR_NO_FILE: // ファイルが選択されていないとき
  84.                         continue 2;
  85.                     case UPLOAD_ERR_INI_SIZE:
  86.                         e("[{$key}] 許可されている最大サイズを超過しました。", $e);
  87.                     case UPLOAD_ERR_PARTIAL:
  88.                         e("[{$key}] ファイルが壊れています。", $e);
  89.                     case UPLOAD_ERR_CANT_WRITE:
  90.                         e("[{$key}] テンポラリデータの生成に失敗しました。", $e);
  91.                     default:
  92.                         e("[{$key}] 不明なエラーが発生しました。", $e);
  93.                 }
  94.                 $tmp_name = $_FILES['upfile']['tmp_name'][$key];
  95.                 if (!is_uploaded_file($tmp_name)) {
  96.                     e("[{$key}] 不正なファイル操作を検知しました。", $e);
  97.                 }
  98.                 // CSVは検知出来なかったのでプレーンテキストならOKとする
  99.                 $finfo = new finfo(FILEINFO_MIME_TYPE);
  100.                 if ($finfo->file($tmp_name) !== 'text/plain') {
  101.                     e("[{$key}] ファイルフォーマットが不正です。", $e);
  102.                 }
  103.                 // 0666にパーミッションを設定
  104.                 chmod($tmp_name, 0666);
  105.                 // 文字コード・改行コードを変換
  106.                 file_put_contents($tmp_name, str_replace(
  107.                     array("\r\n", "\r"),
  108.                     "\n",
  109.                     to_utf8(file_get_contents($tmp_name))
  110.                 ));
  111.                 // ファイル名をステートメントにバインド
  112.                 $stmt->bindValue(1, $tmp_name);
  113.                 // SQL実行
  114.                 $stmt->execute();
  115.                 e("[{$key}] ファイルは正常にインポートされました。", $e);
  116.                
  117.             } catch (Exception $e) { }
  118.            
  119.         }
  120.        
  121.     } catch (Exception $e) { }
  122.    
  123. }
  124.  
  125. header('Content-Type: application/xhtml+xml; charset=utf-8');
  126.  
  127. ?>
  128. <!DOCTYPE html>
  129. <html xmlns="http://www.w3.org/1999/xhtml" lang="ja">
  130.   <head>
  131.     <title>sample</title>
  132.   </head>
  133.   <body>
  134. <?php if ($e !== null): ?>
  135.     <ul>
  136. <?php foreach (exception_to_array($e) as $msg): ?>
  137.       <li><?=htmlspecialchars($msg, ENT_QUOTES, 'UTF-8')?></li>
  138. <?php endforeach; ?>
  139.     </ul>
  140. <?php endif; ?>
  141.     <form action="" method="post" enctype="multipart/form-data">
  142.       <fieldset>
  143.         <legend>CSVファイルを選択</legend>
  144. <?php for ($i = 0; $i < 5; $i++): ?>
  145.         <div><input type="file" name="upfile[]" size="30" /></div>
  146. <?php endfor; ?>
  147.       </fieldset>
  148.       <p><input type="submit" value="アップロード" /></p>
  149.     </form>
  150.   </body>
  151. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement