PHP上傳原理及應用

來源:互聯網
上載者:User

今天看了《 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>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.