PHP上传与下载功能的整合可以通过以下步骤完成:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$uploadPath = 'uploads/' . $fileName;
if(move_uploaded_file($fileTmpName, $uploadPath)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
?>
<a href="download.php?file=example.txt">Download File</a>
<?php
if(isset($_GET['file'])) {
$filePath = 'uploads/' . $_GET['file'];
if(file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
} else {
echo "File not found.";
}
}
?>
通过以上步骤,您可以实现一个简单的PHP上传与下载功能的整合。您也可以根据需求对代码进行定制化的修改和优化。