php 动手实践:文件存储系统
时间: 2023-08-15 16:03:43 浏览: 49
好的,让我们来动手实践一个简单的文件存储系统。
首先,我们需要创建一个 HTML 表单,用于上传文件。在表单中,我们需要添加一个 input 标签,type 属性为 file,还需要添加一个 submit 按钮。
```html
<!DOCTYPE html>
<html>
<head>
<title>File Storage System</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
```
接下来,我们需要编写 PHP 脚本来处理文件上传和存储。我们需要使用 PHP 的 $_FILES 变量来获取上传的文件,并将其移动到我们指定的目录中。在这里,我们将上传的文件存储在名为“uploads”的目录中。
```php
<?php
if(isset($_FILES['file'])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
```
最后,我们需要创建一个简单的文件浏览器,用于显示上传的文件列表。在这里,我们将使用 PHP 的 glob() 函数来获取上传目录中的所有文件,并将它们显示在 HTML 表格中。
```php
<!DOCTYPE html>
<html>
<head>
<title>File Storage System</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
<table>
<thead>
<tr>
<th>Filename</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php
$files = glob('uploads/*');
foreach($files as $file) {
echo "<tr>";
echo "<td>".basename($file)."</td>";
echo "<td>".filesize($file)." bytes</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
```
现在,我们已经完成了一个简单的文件存储系统。用户可以通过上传文件表单将文件上传到服务器,然后通过文件浏览器查看上传的文件列表。