php语言实现上传文件和下载文件
时间: 2024-02-01 11:16:15 浏览: 77
上传文件:
```php
<?php
if(isset($_FILES['file'])) {
$errors = array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$file_ext = strtolower(end(explode('.', $_FILES['file']['name'])));
$extensions = array("jpeg", "jpg", "png");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[] = 'File size must be exactly 2 MB';
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp, "uploads/" . $file_name);
echo "Success";
} else {
print_r($errors);
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
```
下载文件:
```php
<?php
$file = 'example.txt';
if(file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo "File not found.";
}
?>
```
阅读全文