程序来自:PHP与MySQL.WEB开发第三版,最近一直在看这个,我觉得下面的两个程序对学习文件上传很有帮助,现在对他进行一下自已理解的解释。
upload.htm
<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>
upload.php
<html>
<head>
<title>Uploading...</title>
</head>
<body>
<h1>Uploading file...</h1>
<?php
//判断错误的类型
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;
}
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'];
// 判断文件是否是通过 HTTP POST 上传的所以在upload.html处method一定要post
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
$contents = fread ($fp, filesize ($upfile));
fclose ($fp);
//对$contents进行设置
$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>
好了解释就差不多了。