PHP,mySQL初心者です。直接MySQLにバイナリデータを登録するのではなくて、サーバ上のフォルダにアップロードして、そのリンクをMySQLに格納したいと思っています。
参考にさせて頂いたのは下記のサイトです。
[PHP]ファイルアップロードサンプル(PHP → DB → HTML)
上記のサイトを見て、テーブル定義は下記のようにしました。
本当にテーブルの定義名を変えただけなのですが、index.phpの表示は出来て、アップロードしても何も起こらず、DBへの登録もされていません。
何が悪いのか、ご指摘を頂けないでしょうか、または、もっと単純なサンプルコード、書籍ながあれば教えて頂けないでしょうか、どうぞよろしくお願いします。
MySQL
1CREATE TABLE `image_up` ( 2 `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 3 `image_title` varchar(32) DEFAULT NULL, 4 `image_path` varchar(255) DEFAULT NULL, 5 PRIMARY KEY (`id`) 6) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
php
1<?php 2/**common.php*/ 3/**connect_db @return \PDO*/ 4function connect_db() 5{ 6 $dsn = 'mysql:host=----;dbname=----;charset=utf8'; 7 $user = '----'; 8 $pass = '----'; 9 $options = [ 10 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC 11 ]; 12 return new PDO($dsn, $user, $pass, $options); 13} 14 15/**insert* @param string $sql* @param array $arr* @return int lastInsertId*/ 16 17function insert($sql, $arr = []) 18{ 19 $pdo = connect_db(); 20 $stmt = $pdo->prepare($sql); 21 $stmt->execute($arr); 22 return $pdo->lastInsertId(); 23} 24 25/** * select* @param string $sql* @param array $arr* @return array $rows */ 26function select($sql, $arr = []) 27{ 28 $pdo = connect_db(); 29 $stmt = $pdo->prepare($sql); 30 $stmt->execute($arr); 31 return $stmt->fetchAll(); 32} 33/** 34 * htmlspecialchars 35 * @param string $string 36 * @return $string 37 */ 38function h($string) 39{ 40 return htmlspecialchars($string, ENT_QUOTES, 'utf-8'); 41}
php
1<?php 2/*** index.php*/ 3/*** 共通関数読み込み*/ 4require 'common.php'; 5/** 6 * file_upload 7 */ 8function file_upload() 9{ 10 // POSTではないとき何もしない 11 if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') !== 'POST') { 12 return; 13 } 14 // タイトル 15 $image_title = filter_input(INPUT_POST, 'image_title'); 16 if ('' === $image_title) { 17 throw new Exception('タイトルは入力必須です。'); 18 } 19 // アップロードファイル 20 $upfile = $_FILES['upfile']; 21 /*** @see http://php.net/manual/ja/features.file-upload.post-method.php*/ 22 if ($upfile['error'] > 0) { 23 throw new Exception('ファイルアップロードに失敗しました。'); 24 } 25 $tmp_name = $upfile['tmp_name']; 26 // ファイルタイプチェック 27 $finfo = finfo_open(FILEINFO_MIME_TYPE); 28 $mimetype = finfo_file($finfo, $tmp_name); 29 // 許可するMIMETYPE 30 $allowed_types = [ 31 'jpg' => 'image/jpeg' 32 , 'png' => 'image/png' 33 , 'gif' => 'image/gif' 34 ]; 35 if (!in_array($mimetype, $allowed_types)) { 36 throw new Exception('許可されていないファイルタイプです。'); 37 } 38 // ファイル名(ハッシュ値でファイル名を決定するため、同一ファイルは同盟で上書きされる) 39 $filename = sha1_file($tmp_name); 40 // 拡張子 41 $ext = array_search($mimetype, $allowed_types); 42 // 保存作ファイルパス 43 $destination = sprintf('%s/%s.%s', 'upfiles',$filename,$ext); 44 // アップロードディレクトリに移動 45 if (!move_uploaded_file($tmp_name, $destination)) { 46 throw new Exception('ファイルの保存に失敗しました。'); 47 } 48 // Exif 情報の削除 49 $imagick = new Imagick($destination); 50 $imagick->stripimage(); 51 $imagick->writeimage($destination); 52 53 // データベースに登録 54 $sql = 'INSERT INTO image_up ("id","image_title","image_path") VALUES (NULL, :image_title, :image_path) '; 55 $arr = []; 56 $arr[":image_title"] = $image_title; 57 $arr[":image_path"] = $destination; 58 $lastInsertId = insert($sql, $arr); 59 60 // 成功時にページを移動する 61 header(sprintf('Location: image.php?id=%d', $lastInsertId)); 62} 63 64try { 65 // ファイルアップロード 66 file_upload(); 67} catch (Exception $e) { 68 $error = $e->getMessage(); 69} 70?> 71<!DOCTYPE HTML> 72<html lang="ja"> 73 <head> 74 <meta charset="UTF-8"> 75 <title></title> 76 <style type="text/css"> 77 .error { 78 color: red; 79 } 80 </style> 81 </head> 82 <body> 83 <div id="wrap"> 84 <?php if (isset($error)) : ?> 85 <p class="error"><?= h($error); ?></p> 86 <?php endif; ?> 87 <form action="" method="post" enctype="multipart/form-data"> 88 <p> 89 <label for="image_title">タイトル</label> 90 <input type="text" name="image_title" id="image_title" /> 91 </p> 92 <p> 93 <label for="upfile">画像ファイル</label> 94 <input type="file" name="upfile" id="upfile" /> 95 </p> 96 <p> 97 <button type="submit">送信</button> 98 </p> 99 </form> 100 </div> 101 </body> 102</html>
php
1<?php 2/*** image.php*/ 3require 'common.php'; 4try { 5 $id = filter_input(INPUT_GET, 'id'); 6 7 // データベースからレコードを取得 8 $sql = 'SELECT 'id', 'image_title', 'image_path' FROM 'image_up' WHERE 'id' = :id'; 9 $arr = []; 10 $arr[':id'] = $id; 11 $rows = select($sql, $arr); 12 $row = reset($rows); 13} catch (Exception $e) { 14 $error = $e->getMessage(); 15} 16?> 17<!DOCTYPE HTML> 18<html lang="ja"> 19 <head> 20 <meta charset="UTF-8"> 21 <title></title> 22 <style type="text/css"> 23 .error { 24 color: red; 25 } 26 </style> 27 </head> 28 <body> 29 <div id="wrap"> 30 <?php if (isset($error)) : ?> 31 <p class="error"><?= h($error); ?></p> 32 <?php endif; ?> 33 <p><?= h($row['image_title']); ?></p> 34 <p> 35 <img src="<?= h($row['image_path']); ?>" alt="<?= h($row['image_title']); ?>" /> 36 </p> 37 </div> 38 </body> 39</html>
追記:
色々やってみたのですが、まだ解決しません。
さくらのレンタルサーバーではエラーが出力されませんが、アップロードも出来ておらず、php.iniに書き込みもしましたが、やはりエラーがでません。
また、ローカル環境にMAMPで同じ環境を作ったのですが、こちらは下記のようなエラーが出力されています。
Fatal error: Uncaught Error: Class 'Imagick' not found in /Applications/MAMP/htdocs/photo_up/index.php:61 Stack trace: #0 /Applications/MAMP/htdocs/photo_up/index.php(82): file_upload() #1 {main} thrown in /Applications/MAMP/htdocs/photo_up/index.php on line 61
index.phpコードの下記の部分がおかしいようなのですが、MAMP3.5.1のImageMagickは入っていたので、MAMP自体はおかしくないと思われます(ImageMagickについては自分自身は画像を処理してくれるとしか、よくわかっていません)。
```php
$imagick = new Imagick($destination);
$imagick->stripimage();
$imagick->writeimage($destination);
追記02: ローカル環境ではファイルをアップ出来るようになりましたがエラーが出ています。 サーバーはやはりファイルがアップされません 追記03: サーバーにもファイルがアップされました!
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/04 07:59
2017/11/05 15:39
2017/11/05 18:06