0
0

More than 1 year has passed since last update.

PHPで画像アップロード・保存・表示・更新機能を実装してみた

Last updated at Posted at 2023-01-03

画像アップロード・保存・表示・更新機能

PHPで画像アップロード機能を実装しました。
ログイン機能も同時に作っています。

画像をアップロードすると、次の2つのphpファイルの同階層にあるimagesフォルダに
格納されるようになっています。

画像アップロードページ

upload.php
<?php
session_start();
require_once('../classes/UserLogic.php');
require_once('../functions.php');
require_once('../dbconnect.php');

$pdo = connect();

$login_user = $_SESSION['login_user'];
$session_id = $login_user['id'];
$id = $login_user['id'];
$result = UserLogic::checkLogin();

    if (isset($_POST['upload'])) { 
        $image = uniqid(mt_rand(), true); // ファイル名をユニーク化
        // 悪意のあるユーザーに、サーバーに不具合が発生するような名前を設定される恐れがある
        // 長い名前を設定されていると保存できない
        // 保存できないファイル名がある(?.jpgなど)
        $image .= '.' . substr(strrchr($_FILES['image']['name'], '.'), 1); // アップロードされたファイルの拡張子を取得
        $file = "images/$image";
        $stmt = $pdo->prepare("UPDATE gs_users SET image=:image WHERE id=:id;");
        $stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $stmt->bindValue(':image', $image, PDO::PARAM_STR);
        if (!empty($_FILES['image']['name'])) {// ファイルが選択されていればimageにファイル名を代入
            move_uploaded_file($_FILES['image']['tmp_name'], 'images/' . $image); //imagesディレクトリにファイル保存
            if (exif_imagetype($file)) {// 画像ファイルかのチェック
                $message = '画像をアップロードしました';
                $stmt->execute();
            } else {
                $message = '画像ファイルではありません';
            }
        }
    }
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/style.css">
    <title>Document</title>
</head>
    <body>
    <h1>画像アップロード</h1>
    <!-- 送信ボタンが押された場合 -->
    <?php if(isset($_POST['upload'])): ?>
        <p><?php echo $message; ?></p>
        <p><a href="image.php">画像表示へ</a></p>
    <?php else: ?>
    <form method="post" enctype="multipart/form-data">
        <p>アップロード画像選択</p>
        <input type="file" name="image">
        <input type="submit" name="upload" value="送信">        
    </form>
<?php endif; ?>  
    </body>
</html>

アップロードされた画像を確認するページ

image.php
<?php
require_once('../classes/UserLogic.php');
require_once('../functions.php');
require_once('../dbconnect.php');
session_start();

$pdo = connect();

$result = UserLogic::checkLogin();

$login_user = $_SESSION['login_user'];
$session_id = $login_user['id'];
$id = $login_user['id'];


if (!$result) {
  $_SESSION['login_err'] = 'ユーザを登録してログインしてください!';
  header('Location: login_form.php');
  return;
}
    $stmt = $pdo->prepare("SELECT * FROM gs_users WHERE id=:id");
    $stmt->bindValue(':id', $id);
    $stmt->execute();
    $image = $stmt->fetch(); 
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./css/style.css">
  <title>Document</title>
</head>
  <body>
<div class="work-img">
  <h1>作品画像表示</h1>
  <img src="images/<?php echo $image['image']; ?>" max-width="500" height="800">
</div>
<div class="tac">
  <a href="upload.php">アップロード画像を更新する</a>
</div>
  </body>
</html>

プログラミング初心者です。問題があれば指摘していただけると大変ありがたいです。

この記事は以下の情報を参考にして執筆しました。ありがとうございました。
https://qiita.com/ryo-futebol/items/11dea44c6b68203228ff

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0