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 }?>