莱因电博

Li-e.cn

Li Internet Electronic Blog
@rss

一个简单的PHP上传下载实例

————————————————————

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>文件管理</title>
	</head>
		
		<h2>文件上传</h2>
		<hr width="30%" align="left">
		
		<form action="upload_file.php" method="post" enctype="multipart/form-data">
			请选择您要上传的文件:<input type="file" name="myFile" /><br/>
			<input type="submit" value="上传"/>
		</form>
		<br>
		
		<h2>文件下载</h2>
		<hr width="30%" align="left">
		
		<form action="download_file.php" method="get">
			<input  name="filename" type="text" style="width: 17%;" value="" placeholder="请输入文件名" />
			<input type="submit" value="下载" />
		</form>
		
	</body>
</html>

upload_file.php

<?php
 
    header("Content-Type:text/html;charset=utf8");

    $dir = 'upload/';
    //  获取文件名
    $filename = $_FILES['myFile']['name'];
    $tmp_name = $_FILES['myFile']['tmp_name'];
    //  判断文件是否通过 POST 方式 并 成功上传
    if(is_uploaded_file($tmp_name))
    {
        if(move_uploaded_file($tmp_name,$dir.$filename))
        {
            $tip = "[$filename] 上传成功: [$dir]";
        }
        else{
            $tip = "[$filename] 上传失败";
        }
    }
    else{
        $tip = "非法上传";
    }
    
    echo $tip;
?>

download_file.php

<?php

	//header("Content-Type:text/html;charset=utf8");
	
	$file_name = $_GET['filename'];		
	$download_path = "upload/";
 
	if(!file_exists($download_path.$file_name)){
			
        Header("Content-type:text/html;charset=utf-8");	
        echo "文件不存在!</br>";

        exit;
	}
	else{
        			
        $file=fopen($download_path.$file_name,"r");
		
	    header('Content-Typr:application/octet-stream');
	    header("Accept-Ranges: bytes");
	    header("Content-Disposition:attachment;filename=".$file_name);
	    header('Content-length:'.filesize($download_path.$file_name));
	
	    readfile($download_path.$file_name);
    }
?>

info.php

<?php
phpinfo();
?>
(C) 2019 - 2024 Li-e.cn莱因电博(立网电子博客) | Powered by Vercel , based on Hugo with Gists theme.