PHP上传实例代码 防止重复上传,本上传实例代码非常合适php新手学习,有详细的注解。
<?php
session_start();
/******以下可用来跟踪用户
$sess_id = session_id();
$id = rand(100000000000000,9999999999999999);
******/
if( $_POST["Submit"]){
/******以下是防止重复上传,适用只允许上传一次
if( $_SESSION["name"] == "1"){
echo "<p>请不要重复提交!</p>";
exit;
}
******/
$file_name = $_FILES["file"]["name"];
$file_size = $_FILES["file"]["size"];
$file_type = $_FILES["file"]["type"];
$file_tn = time(). $file_name;
$save_path = "upfiles/";
$messg = "<p>上传文件发生以外:</p><a href='?id=". $id."'>返回重试</a>";
$messg_sr = $messg;
if( $file_type != "application/msword"){//清风提示,这里限制上传格式为word
$messg .= "<p>本次上传文件格式为MS WORD,通常扩展名为.doc</p>";
}
if( $file_size > 1048576){//清风提示,这里可写成"if( $file_size > 1*1024*1024){"方便修改
$messg .= "<p>本次上传文件大小不能超过1MB,本文件大小为".round(( $file_size/1024/1024),2)."MB</p>";
}
if( $messg != $messg_sr){
echo $messg;
}else{
if(move_uploaded_file( $_FILES["file"]["tmp_name"], $save_path. $file_tn)){
// $_SESSION["name"] = "1";#防止重复上传和上面对应
//以下是上传成功的各种提示及跳转
//echo "<p>恭喜你!上传文件成功。</p>";
//echo "<script language='javascript'>close();</script>";
//echo "<script>location.href='';</script>";
//echo "<meta http-equiv="refresh" content="0;URL=http://domain.com/test.html">";#原型
echo "<meta http-equiv="refresh" content="3;URL=/"><div id="container" style="margin:40px; padding:40px;text-align:center; font-size:12px; border:#0099FF double;">上传成功!</div>";
}else{
echo $messg;
}
}
}else{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>文件上传</title>
<style type="text/css">
<!--
.pt11 {
font-size: 11pt;
color: #333333;
}
-->
</style>
</head>
<body>
<form id="form1" name="form1" method="post" enctype="multipart/form-data" action="">
<table width="500" border="0" align="center" cellspacing="1" bgcolor="#666699" class="pt11">
<tr>
<td height="25" bgcolor="#9999FF">上传</td>
</tr>
<tr>
<td height="60" align="center" bgcolor="#F1F1F1">
<input name="file" type="file" id="file" size="32" />
</td>
</tr>
<tr>
<td height="25" align="center" bgcolor="#E1E1E1">
<input type="submit" name="Submit" value="提 交" /></td>
</tr>
</table>
</form>
</body>
</html>
<?php }?>