Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * 文字コードをUTF-8に変換
- */
- function to_utf8($str) {
- return mb_convert_encoding(
- $str,
- 'UTF-8',
- 'ASCII,JIS,UTF-8,CP51932,SJIS-win'
- );
- }
- /**
- * 例外スタックを古い順にして配列に変換
- */
- function exception_to_array($e) {
- do {
- $messages[] = $e->getMessage();
- } while($e = $e->getPrevious());
- return array_reverse($messages);
- }
- /**
- * 例外をスロー
- */
- function e($message, $previous = null) {
- throw new RuntimeException(to_utf8($message), 0, $previous);
- }
- // 例外変数初期化
- $e = null;
- if (isset($_FILES['upfile'])) {
- try {
- /* データベース接続 */
- // PDOオブジェクト生成
- $pdo = new PDO(
- 'mysql:dbname=shop;host=127.0.0.1;charset=utf8',
- 'user',
- 'password',
- array(
- // エラーモードを例外スローに設定
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- // LOAD DATA INFILE する際には character_set_database の適切な指定が必要
- PDO::MYSQL_ATTR_INIT_COMMAND => 'SET character_set_database=utf8',
- )
- );
- // プリペアドステートメント生成
- $stmt = $pdo->prepare(implode(' ', array(
- 'LOAD DATA INFILE ?',
- 'INTO TABLE `food`',
- 'FIELDS',
- 'TERMINATED BY ?',
- 'ENCLOSED BY ?',
- 'LINES TERMINATED BY ?',
- 'IGNORE 1 LINES',
- )));
- // 固定値はすぐバインド
- $stmt->bindValue(2, ',');
- $stmt->bindValue(3, '"');
- $stmt->bindValue(4, "\n");
- /* パラメータチェック1 */
- if (!is_array($_FILES['upfile']['error'])) {
- e('パラメータが不正です。', $e);
- }
- /* パラメータチェック2 & SQL実行 */
- foreach ($_FILES['upfile']['error'] as $key => $error) {
- try {
- if (is_array($error)) {
- e("[{$key}] パラメータが不正です。", $e);
- }
- switch ($error) {
- case UPLOAD_ERR_OK: // エラーが何もない時
- break;
- case UPLOAD_ERR_NO_FILE: // ファイルが選択されていないとき
- continue 2;
- case UPLOAD_ERR_INI_SIZE:
- e("[{$key}] 許可されている最大サイズを超過しました。", $e);
- case UPLOAD_ERR_PARTIAL:
- e("[{$key}] ファイルが壊れています。", $e);
- case UPLOAD_ERR_CANT_WRITE:
- e("[{$key}] テンポラリデータの生成に失敗しました。", $e);
- default:
- e("[{$key}] 不明なエラーが発生しました。", $e);
- }
- $tmp_name = $_FILES['upfile']['tmp_name'][$key];
- if (!is_uploaded_file($tmp_name)) {
- e("[{$key}] 不正なファイル操作を検知しました。", $e);
- }
- // CSVは検知出来なかったのでプレーンテキストならOKとする
- $finfo = new finfo(FILEINFO_MIME_TYPE);
- if ($finfo->file($tmp_name) !== 'text/plain') {
- e("[{$key}] ファイルフォーマットが不正です。", $e);
- }
- // 0666にパーミッションを設定
- chmod($tmp_name, 0666);
- // 文字コード・改行コードを変換
- file_put_contents($tmp_name, str_replace(
- array("\r\n", "\r"),
- "\n",
- to_utf8(file_get_contents($tmp_name))
- ));
- // ファイル名をステートメントにバインド
- $stmt->bindValue(1, $tmp_name);
- // SQL実行
- $stmt->execute();
- e("[{$key}] ファイルは正常にインポートされました。", $e);
- } catch (Exception $e) { }
- }
- } catch (Exception $e) { }
- }
- header('Content-Type: application/xhtml+xml; charset=utf-8');
- ?>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml" lang="ja">
- <head>
- <title>sample</title>
- </head>
- <body>
- <?php if ($e !== null): ?>
- <ul>
- <?php foreach (exception_to_array($e) as $msg): ?>
- <li><?=htmlspecialchars($msg, ENT_QUOTES, 'UTF-8')?></li>
- <?php endforeach; ?>
- </ul>
- <?php endif; ?>
- <form action="" method="post" enctype="multipart/form-data">
- <fieldset>
- <legend>CSVファイルを選択</legend>
- <?php for ($i = 0; $i < 5; $i++): ?>
- <div><input type="file" name="upfile[]" size="30" /></div>
- <?php endfor; ?>
- </fieldset>
- <p><input type="submit" value="アップロード" /></p>
- </form>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement