2011年4月11日 星期一

使用 PHP 上傳檔案

必須將表單中的 enctype 屬性設成 multipart/form-data。enctype 屬性是指定瀏覽器對表單中的參數進行編碼的方法,預設值為 application/x-www-form-urlencoded。
以下是建立表單的例子:
upload.html

01 <html>
02 <head>
03 <title>A simple upload form</title>
04 </head>
05 <body>
06 <h2>A simple upload form</h2>

07
08 <form method="post" action="upload.php" enctype="multipart/form-data">
09 Enter file name: <input type="file" name="userfile"><br>
10 <input type="submit" value="Upload">
11 </form>
12
13 </body>
14 </html>

處理上傳檔案



建立了以上的 HTMl 表單後,下一步要做的就是後端的處理。在 PHP 中可以透過二維陣列 $HTTP_POST_FILES 或 $_FILES 來存取所上傳的檔案詳細內容。就以以上表單為例,輸入元素名為 userfile,各陣列元素為:
$_FILES['userfile']['name'] -- 檔案在客戶端電腦上的檔案名稱
$_FILES['userfile']['type'] -- 檔案的 MIME 類型,例如 "image/gif"
$_FILES['userfile']['size'] -- 上傳檔案的檔案大小,單為為 bytes
$_FILES['userfile']['tmp_name'] -- 上傳檔案儲存在伺服器端的暫存檔案名
$_FILES['userfile']['error'] -- 在 PHP 4.2.0 或更新的片本才有的這個陣列元素,上傳檔案的錯誤號碼

上傳檔案的 PHP 程式


<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\\\\n";
} else {
echo "Possible file upload attack!\\\\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

多檔同時傳送陣列實例:

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>

沒有留言:

張貼留言

Google Analytics初學者入門簡介