Skip to content

Instantly share code, notes, and snippets.

@codeforfun-jp
Created August 23, 2022 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeforfun-jp/8f35be41006971b02a09cd3ea354f6ec to your computer and use it in GitHub Desktop.
Save codeforfun-jp/8f35be41006971b02a09cd3ea354f6ec to your computer and use it in GitHub Desktop.
Save Image File with PHP & MySQL - #7-1
<?php
require_once('functions.php');
$pdo = connectDB();
$err_msg = '';
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
// 画像を取得
$sql = 'SELECT * FROM images ORDER BY created_at DESC';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$images = $stmt->fetchAll();
} else {
// 画像を保存
if (!empty($_FILES['image']['name'])) {
$name = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$content = file_get_contents($_FILES['image']['tmp_name']);
$size = $_FILES['image']['size'];
// 画像の形式チェック
$validFileTypes = ['image/png', 'image/jpeg'];
if (!in_array($type, $validFileTypes)) {
$err_msg = '* jpg, jpeg, png 形式のファイルを選択してください。';
}
if ($err_msg == '') {
$sql = 'INSERT INTO images(image_name, image_type, image_content, image_size, created_at)
VALUES (:image_name, :image_type, :image_content, :image_size, now())';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':image_name', $name, PDO::PARAM_STR);
$stmt->bindValue(':image_type', $type, PDO::PARAM_STR);
$stmt->bindValue(':image_content', $content, PDO::PARAM_STR);
$stmt->bindValue(':image_size', $size, PDO::PARAM_INT);
$stmt->execute();
header('Location:list.php');
exit();
}
}
}
?>
<!DOCTYPE html>
<html lang="ja">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment