简单的文件上传API,保存在 ./files 目录下,返回文件的完整 URL。
- <?php
- $allowedExtensions = ['zip', 'jpg', 'jpeg', 'png', 'gif'];
- $uploadDir = './files/';
- if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- if (!empty($_FILES['file']) && $_FILES['file']['error'] === 0) {
- $filename = $_FILES['file']['name'];
- $tempFilePath = $_FILES['file']['tmp_name'];
- $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
- $mime = mime_content_type($tempFilePath);
- if (in_array($extension, $allowedExtensions) && in_array($mime, ['application/zip', 'image/jpeg', 'image/png', 'image/gif'])) {
- $newFilename = uniqid() . '.' . $extension;
- $destination = $uploadDir . $newFilename;
- if (move_uploaded_file($tempFilePath, $destination)) {
- $url = 'https://' . $_SERVER['HTTP_HOST'] . '/files/' . $newFilename;
- echo $url;
- exit;
- } else {
- echo '文件上传失败';
- }
- } else {
- echo '不支持的文件类型';
- }
- } else {
- echo '上传文件失败';
- }
- }
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <title>文件上传示例</title>
- </head>
- <body>
- <form action="file.php" method="post" enctype="multipart/form-data">
- <label for="file">选择文件:</label>
- <input type="file" name="file" id="file" accept=".zip,.jpg,.jpeg,.png,.gif">
- <button type="submit">上传文件</button>
- </form>
- </body>
- </html>