温馨提示×

debian php中如何实现文件上传下载

PHP
小樊
87
2024-08-14 12:46:39
栏目: 编程语言

文件上传:

  1. 在HTML表单中添加一个文件上传的input标签:
<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>
  1. 创建一个PHP处理文件上传的脚本upload.php:
<?php
$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.";
}
?>

文件下载:

  1. 创建一个PHP脚本download.php来处理文件下载请求:
<?php
$file = 'path/to/file.txt';
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;
?>
  1. 在需要提供文件下载的页面中创建一个链接指向download.php,传递文件名参数:
<a href="download.php?file=file.txt">Download file</a>

0