今天看了《 PHP上傳原理及其應用》的視頻,基本瞭解了php的檔案上傳的方法,最主要的兩個函數是move_uploade_file(臨時檔案,目標位置和檔案名稱)和is_uploaded_file(),前者用來移動上傳後儲存在伺服器緩衝區的檔案到目標檔案,後者用來判斷檔案是否上傳成功。
除了以上兩個函數之外,還要說明一下form標籤中enctype的值應該如下:
<form enctype="multipart/form-data" method="post" name="upform">
只有其值為multipart/form-data才能保證以正確的編碼方式上傳檔案。
input標籤 type 屬性中的 "file"
<input name="upfile" type="file">
另一個系統函數是$_FILES
$_FILES['myFile']['name'] 用戶端檔案的原名稱。
$_FILES['myFile']['type'] 檔案的 MIME 類型,例如"image/gif"。
$_FILES['myFile']['size'] 已上傳檔案的大小,單位為位元組。
$_FILES['myFile']['tmp_name'] 儲存的臨時檔案名稱,一般是系統預設。
$_FILES['myFile']['error'] 該檔案上傳相關的錯誤碼。
這個函數將上傳檔案的資訊分割成數組形式儲存在不同的數組元素中,例如,檔案名稱的值儲存在$_FILES['myFile']['name']中。
下面附上自己寫的簡單的php檔案上傳程式:
-----------------------類saveupload.php---------------------
<?php
if(is_uploaded_file($_FILES['upfile']['tmp_name'])){
$upfile = $_FILES["upfile"] ;//如果已經選定了要上傳的檔案,將其索引儲存在$upfile 中
//分別去上傳檔案的名字,類型等
$name = $upfile["name"] ;
$type = $upfile["type"] ;
$size = $upfile["size"] ;
$tmp_name = $upfile["tmp_name"] ;
$error = $upfile["error"] ;
//設定上傳檔案類型
switch($type){
case 'image/pjpeg' :
$ok = 1 ;
break ;
case 'image/jpeg' :
$ok = 1 ;
break ;
case 'image/png' :
$ok = 1 ;
break ;
case 'image/gif' :
$ok = 1 ;
break ;
}
//如果檔案類型合法並且$error傳回值為0,說明上傳成功
if($ok && $error=='0'){
move_uploaded_file($tmp_name , 'up/'.$name) ;//將儲存在緩衝的檔案移動到指定目錄下
echo "上傳成功" ;
}
}
?>
--------------------------上傳頁面upload.php---------------
<!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=utf-8" />
<title>upload</title>
<style type="text/css">
<!--
body {
background-color: #CFF;
text-align: center;
}
-->
</style></head>
<body>
檔案上傳
<hr />
<form id="form1" name="form1" method="post" action="saveupload.php" enctype="multipart/form-data">
上傳檔案:
<label>
<input type="file" name="upfile" />
</label>
<label>
<input type="submit" name="button" id="button" value="上傳" />
</label>
</form>
</body>
</html>