以下正文:
1.先来个请求页面upload.html
<html>
<head>
<title>administration - upload new files</title>
</head>
<body>
<h1>upload new news files</h1>
<form enctype="multipart/form-data" action="upload.php" method=post>
<input type="hidden" name="max_file_size" value="1000000">
upload this file: <input name="userfile" type="file">
<input type="submit" value="send file">
</form>
</body>
</html>
2.php处理客户端请求的数据upload.php
<html>
<head>
<title>uploading...</title>
</head>
<body>
<h1>uploading file...</h1>
<?php
//check to see if an error code was generated on the upload attempt
if ($_files['userfile']['error'] > 0)
{
echo 'problem: ';
switch ($_files['userfile']['error'])
{
case 1: echo 'file exceeded upload_max_filesize';
break;
case 2: echo 'file exceeded max_file_size';
break;
case 3: echo 'file only partially uploaded';
break;
case 4: echo 'no file uploaded';
break;
case 6: echo 'cannot upload file: no temp directory specified.';
break;
case 7: echo 'upload failed: cannot write to disk.';
break;
}
exit;
}
// does the file have the right mime type?
if ($_files['userfile']['type'] != 'text/plain')
{
echo 'problem: file is not plain text';
exit;
}
// put the file where we'd like it
$upfile = '/uploads/'.$_files['userfile']['name'];
if (is_uploaded_file($_files['userfile']['tmp_name']))
{
if (!move_uploaded_file($_files['userfile']['tmp_name'], $upfile))
{
echo 'problem: could not move file to destination directory';
exit;
}
}
else
{
echo 'problem: possible file upload attack. filename: ';
echo $_files['userfile']['name'];
exit;
}
echo 'file uploaded successfully<br><br>';
// reformat the file contents
$fp = fopen($upfile, 'r');
$contents = fread ($fp, filesize ($upfile));
fclose ($fp);
$contents = strip_tags($contents);
$fp = fopen($upfile, 'w');
fwrite($fp, $contents);
fclose($fp);
// show what was uploaded
echo 'preview of uploaded file contents:<br><hr>';
echo $contents;
echo '<br><hr>';
?>
</body>
</html>
3.php文件下载
<?php
$filepath = "template/";//此处给出你下载的文件在服务器的什么地方
$filename = "template.xls";
//此处给出你下载的文件名
$file = fopen($filepath . $filename, "r"); // 打开文件
//输入文件标签
header("content-type:application/octet-stream ");
header("accept-ranges:bytes ");
header("accept-length: " . filesize($filepath . $filename));
header("content-disposition: attachment; filename= " . $filename);
// 输出文件内容
echo fread($file, filesize($filepath . $filename));
fclose($file);
exit;
?>
以上就是(进阶篇)php的文件上传与下载实例的内容。