How to write a simple online storage system through PHP
In the current digital era, data storage and management have become crucial. For developers, building a simple online storage system can easily save and retrieve data. This article will introduce how to use PHP to write a simple online storage system and provide specific code examples.
<!DOCTYPE html> <html> <head> <title>文件上传</title> </head> <body> <h1>文件上传</h1> <form enctype="multipart/form-data" action="upload.php" method="POST"> <input type="file" name="file" required> <input type="submit" value="上传"> </form> </body> </html>
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $file = $_FILES['file']; $fileName = $file['name']; $fileSize = $file['size']; $fileContent = file_get_contents($file['tmp_name']); // 连接数据库并保存文件信息 $conn = new mysqli('localhost', '用户名', '密码', '数据库名'); $sql = "INSERT INTO files (name, size, content, created_at, updated_at) VALUES ('$fileName', '$fileSize', '$fileContent', now(), now())"; $conn->query($sql); $conn->close(); echo '文件上传成功!'; } ?>
<?php // 连接数据库并获取文件列表 $conn = new mysqli('localhost', '用户名', '密码', '数据库名'); $sql = "SELECT * FROM files"; $result = $conn->query($sql); $files = $result->fetch_all(MYSQLI_ASSOC); $conn->close(); ?> <!DOCTYPE html> <html> <head> <title>文件列表</title> </head> <body> <h1>文件列表</h1> <table> <tr> <th>ID</th> <th>文件名称</th> <th>文件大小</th> <th>创建时间</th> </tr> <?php foreach ($files as $file): ?> <tr> <td><?php echo $file['id']; ?></td> <td><?php echo $file['name']; ?></td> <td><?php echo $file['size']; ?></td> <td><?php echo $file['created_at']; ?></td> </tr> <?php endforeach; ?> </table> </body> </html>
Now you can upload files by accessing 'index.php' and add them by accessing 'files.php 'View the list of uploaded files.
Through the steps in this article, you have successfully written a simple online storage system. Of course, there are still many functions that need to be further improved in practical applications, such as file downloading, editing and deletion. But these can all serve as directions for further learning and expansion. Happy programming!
The above is the detailed content of How to write a simple online storage system through PHP. For more information, please follow other related articles on the PHP Chinese website!