PHP:シンプルな音楽のアップロードと表示

知識ポイント

ファイルのディレクトリ

Add.php├──
├──bootstrap.css
├──list.php
├──storage.json
├──アップロード(空のフォルダ)

コアコード

// list.php
<?php

// 获取文件中记录的数据,并展示到表格中(动态生成表格的HTML标签)
$contents = file_get_contents('storage.json');
// $contents => JSON 格式的字符串
// 把 JSON 格式的字符串转换为对象的过程叫做反序列化

// json_decode 默认反序列化时 将 JSON 中的对象转换为 PHP 中 stdClass 类型的对象
$data = json_decode($contents, true);
// $data => []

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>音乐列表</title>
  <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
  <div class="container py-5">
    <h1 class="display-4">音乐列表</h1>
    <hr>
    <div class="mb-3">
      <a href="add.php" class="btn btn-secondary btn-sm">添加</a>
    </div>
    <table class="table table-bordered table-striped table-hover">
      <thead class="thead-dark">
        <tr>
          <th class="text-center">标题</th>
          <th class="text-center">歌手</th>
          <th class="text-center">海报</th>
          <th class="text-center">音乐</th>
          <th class="text-center">操作</th>
        </tr>
      </thead>
      <tbody class="text-center">
        <?php foreach ($data as $item): ?>
        <tr>
          <td><?php echo $item['title'] ?></td>
          <td><?php echo $item['artist'] ?></td>
          <td><img src="<?php echo $item['images'][0] ?>" alt=""></td>
          <td><audio src="<?php echo $item['source'] ?>" controls></audio></td>
          <td><button class="btn btn-danger btn-sm">删除</button></td>
        </tr>
        <?php endforeach ?>
      </tbody>
    </table>
  </div>
</body>
</html>

// add.php
<?php

/**
 * 只是在表单提交时执行
 */
function add_music () {
  // 目标
  //  将用户提交过来的数据保存到 storage.json 中
  // 步骤
  //  1. 接收并校验
  //  2. 持久化
  //  3. 响应

  // 文本框校验
  // =====================================================

  if (empty($_POST['title'])) {
    $GLOBALS['error_message'] = '请输入标题';
    return;
  }

  if (empty($_POST['artist'])) {
    $GLOBALS['error_message'] = '请输入歌手';
    return;
  }

  // 校验上传文件
  // =====================================================

  if (empty($_FILES['source'])) {
    // 客户端提交的表单中没有 source 文件域
    $GLOBALS['error_message'] = '请正确提交文件';
    return;
  }

  $source = $_FILES['source'];

  // 判断用户是否选择了文件
  if ($source['error'] !== UPLOAD_ERR_OK) {
    $GLOBALS['error_message'] = '请选择音乐文件';
    return;
  }

  // 校验文件的大小
  if ($source['size'] > 10 * 1024 * 1024) {
    $GLOBALS['error_message'] = '音乐文件过大';
    return;
  }

  if ($source['size'] < 1 * 1024 * 1024) {
    $GLOBALS['error_message'] = '音乐文件过小';
    return;
  }

  // 校验类型
  $allowed_types = array('audio/mp3', 'audio/wma');
  if (!in_array($source['type'], $allowed_types)) {
    $GLOBALS['error_message'] = '这是不支持的音乐格式';
    return;
  }

  // 音乐文件已经上传成功,但是还在临时目录中
  // 一般情况会将上传的文件重命名
  $target = './uploads/' . uniqid() . '-' . $source['name'];
  if (!move_uploaded_file($source['tmp_name'], $target)) {
    $GLOBALS['error_message'] = '上传音乐失败';
    return;
  }

  // =========== 接收图片 ==============

  if (empty($_FILES['images'])) {
    // 客户端提交的表单中没有 source 文件域
    $GLOBALS['error_message'] = '请正确提交文件';
    return;
  }

  $images = $_FILES['images'];

  // 判断用户是否选择了文件
  if ($images['error'] !== UPLOAD_ERR_OK) {
    $GLOBALS['error_message'] = '请选择图片文件';
    return;
  }

  // 校验文件的大小

  if ($images['size'] > 1 * 1024 * 1024) {
    $GLOBALS['error_message'] = '图片文件过大';
    return;
  }

  // 校验类型
  $allowed_types = array('image/jpeg', 'image/png', 'image/gif');
  if (!in_array($images['type'], $allowed_types)) {
    $GLOBALS['error_message'] = '这是不支持的图片格式';
    return;
  }

  // 音乐文件已经上传成功,但是还在临时目录中
  // 一般情况会将上传的文件重命名
  $target = './uploads/' . uniqid() . '-' . $images['name'];
  if (!move_uploaded_file($images['tmp_name'], $target)) {
    $GLOBALS['error_message'] = '上传图片失败';
    return;
  }

  // 图片音乐都上传成功
  $title = $_POST['title'];
  $artist = $_POST['artist'];
  $images = '图片';
  $source = '音乐';

  $origin = json_decode(file_get_contents('storage.json'), true);

  $origin[] = array(
    'id' => uniqid(),
    'title' => $_POST['title'],
    'artist' => $_POST['artist'],
    'images' => '123',
    'source' => '1231',
  );

  $json = json_encode($origin);

  file_put_contents('storage.json', $json);

  // 跳转回列表页
  header('Location: list.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  add_music();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>添加新音乐</title>
  <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
  <div class="container py-5">
    <h1 class="display-4">添加新音乐</h1>
    <hr>
    <?php if (isset($error_message)): ?>
    <div class="alert alert-danger" role="alert">
      <?php echo $error_message; ?>
    </div>
    <?php endif ?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" autocomplete="off">
      <div class="form-group">
        <label for="title">标题</label>
        <input type="text" class="form-control" id="title" name="title">
      </div>
      <div class="form-group">
        <label for="artist">歌手</label>
        <input type="text" class="form-control" id="artist" name="artist">
      </div>
      <div class="form-group">
        <label for="images">海报</label>
        <input type="file" class="form-control" id="images" name="images">
      </div>
      <div class="form-group">
        <label for="source">音乐</label>
        <!-- accept 可以限制文件域能够选择的文件种类,值是 MIME Type -->
        <input type="file" class="form-control" id="source" name="source" accept="audio/*">
      </div>
      <button class="btn btn-primary btn-block">保存</button>
    </form>
  </div>
</body>
</html>

[
  {
    "id": "59d632855434e",
    "title": "\u9519\u8fc7",
    "artist": "\u6881\u548f\u742a",
    "images": [
      "\/uploads\/img\/1.jpg"
    ],
    "source": "\/uploads\/mp3\/1.mp3"
  },
  {
    "id": "59d632855434f",
    "title": "\u5f00\u59cb\u61c2\u4e86",
    "artist": "\u5b59\u71d5\u59ff",
    "images": [
      "\/uploads\/img\/2.jpg"
    ],
    "source": "\/uploads\/mp3\/2.mp3"
  },
  {
    "id": "59d6328554350",
    "title": "\u4e00\u751f\u4e2d\u6700\u7231",
    "artist": "\u8c2d\u548f\u9e9f",
    "images": [
      "\/uploads\/img\/3.jpg"
    ],
    "source": "\/uploads\/mp3\/3.mp3"
  },
  {
    "id": "59d6328554351",
    "title": "\u7231\u5728\u6df1\u79cb",
    "artist": "\u8c2d\u548f\u9e9f",
    "images": [
      "\/uploads\/img\/4.jpg"
    ],
    "source": "\/uploads\/mp3\/4.mp3"
  },
  {
    "id": "59f0592aa33d8",
    "title": "123123",
    "artist": "123123",
    "images": "123",
    "source": "1231"
  }
]
公開された165元の記事 ウォン称賛59 ビュー30000 +

おすすめ

転載: blog.csdn.net/weixin_43972437/article/details/103635152