PHP教程:一些相关常用PHP实例(2)
5.4 文件上传
你可以利用PHP实现文件的功能,注意客户端的浏览器应该是Netscape3以上或者IE3以上。以下就是该功能的简单演示:
( upload.html ):
<HTML>
<HEAD>
<TITLE>Upload Your File</TITLE>
</HEAD>
<BODY>
<FORM ACTION="receiver.php3"
ENCTYPE="multipart/form-data" METHOD=POST>
<INPUT TYPE="HIDDEN"
NAME="MAX_FILE_SIZE" VALUE="2000000">
<INPUT TYPE="FILE"
NAME="uploadfile" SIZE="24" MAXLENGTH="80">
<BR><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload File!"
NAME="sendit">
<INPUT TYPE="SUBMIT" VALUE="Cancel"
NAME="cancelit"><BR>
</FORM>
<I><FONT SIZE="2">(You may notice a slight
delay while we upload your file.)</FONT></I>
</BODY>
</HTML>
下面是处理上传的文件:
( receiver.php3 ):
<?
function do_upload ()
{
global $uploadfile, $uploadfile_size;
global $local_file, $error_msg;
if ( $uploadfile == "none" )
{
$error_msg = "You did not specify a file for uploading.";
return;
}
if ( $uploadfile_size > 2000000 )
{
$error_msg = "Sorry, your file is too large.";
return;
}
$the_time = time ();
// 你需要对以下目录有写权限
$upload_dir = "/local/uploads";
$local_file = "$upload_dir/$the_time";
if ( file_exists ( '$local_file' ) )
{
$seq = 1;
while ( file_exists ( "$upload_dir/$the_time$seq" ) ) { $seq++; }
$local_file = "$upload_dir/$the_time$seq";
};
rename ( $uploadfile, $local_file );
display_page ();
}
function display_page ()
{
// 这里是你的页面内容
}
<HTML>
<HEAD>
<TITLE>php3 Receiving Script</TITLE>
</HEAD>
<BODY>
<?
if ( $error_msg ) { echo "<B>$error_msg</B><BR><BR>"; }
if ( $sendit )
{
do_upload ();
}
elseif ( $cancelit )
{
header ( "Location: $some_other_script" );
exit;
}
else
{
some_other_func ();
}
?>
</BODY>
</HTML>