談談php中上傳檔案的處理

2022-02-09 04:03:00 字數 3082 閱讀 5717

這是乙個表單的時代。。。

我們在瀏覽器中編輯自己的資訊,會遇到上傳頭像;在文庫中,我們會上傳文件......到處存在「上傳」這個詞。

php是最好的語言(其他語言的程式猿們不要打我...)。php在處理互動方面有天然的優勢,自然有強大的函式來處理上傳檔案。

和提交一般的資料一樣,上傳檔案也需要表單。下面建立乙個特殊的表單來上傳檔案。

1

<

form

enctype

="multipart/form-data"

action

="upload_file.php"

name

="upload_form"

method

="post"

>23

<

input

type

="hidden"

name

="max_file_size"

value

="30000"

/>

4上傳的檔案:

5<

input

type

="file"

name

="userfile"

/>

6<

hr/>

7<

input

type

="submit"

name

="sub_button"

value

="上傳檔案的提交按鈕"

/>89

form

>

ok,我們分析一下這個**段。

以上的enctype規定了資料在傳送給伺服器的時候採用什麼編碼格式。它有三個值:

max_file_size隱藏字段(單位為位元組)必須放在檔案輸入字段之前,其值為檔案的最大尺寸。這是對瀏覽器的乙個建議,php也會檢查此項。不過在瀏覽器端可以繞過這個障礙,因此不要指望用它來阻擋大檔案。但是檔案最大值受php.ini中的post_max_size= (number)m的限制。但是最好還是加上這個專案,它可以避免使用者在花時間等待上傳大檔案之後才發現大檔案上傳失敗的麻煩。

在使用者提交檔案表單之後,伺服器端就可以接受資料了。php中有全域性變數$_files來處理檔案,假設上傳欄位名稱為userfile(可以在字段中隨意更改)。

$_files['userfile']['name']                客戶端檔案的原名稱。

$_files['userfile']['type']                 檔案的mime型別,這個在php端並不檢查,因此這個值還不一定有。   

$_files['userfile']['size']                  上傳的檔案的大小(單位位元組)。

$_files['userfile']['tmp_name']         檔案上傳後在伺服器端儲存的臨時檔名。

$_files['userfile']['error']                 和該檔案上傳相關的錯誤**。如果上傳成功,值為0.

檔案在上傳後,預設儲存到伺服器預設臨時目錄中,在php.ini中的upload_tmp_dir設定為其他路徑。

在這裡還得說說乙個move_uploaded_file()函式:

這個函式檢查並確保由 file 指定的檔案是合法的上傳檔案(即通過 php 的 http post 上傳機制所上傳的)。如果檔案合法,則將其移動為由 newloc 指定的檔案。

如果 file 不是合法的上傳檔案,不會出現任何操作,move_uploaded_file() 將返回 false。

如果 file 是合法的上傳檔案,但出於某些原因無法移動,不會出現任何操作,move_uploaded_file() 將返回 false,此外還會發出一條警告。

這種檢查顯得格外重要,如果上傳的檔案有可能會造成對使用者或本系統的其他使用者顯示其內容的話。

下面是乙個php上傳檔案例項:

1

<

b>上傳檔案處理

b>

2<

hr/>

3php4

if (isset($_files['userfile'])) else

13echo '這是上傳檔案的一些資訊:' . '

';14

print_r($_files);

15echo '';

16die();17}

1819

?>

20<

b>上傳表單

b>

2122

<

form

enctype

="multipart/form-data"

action

="upload_file.php"

name

="upload_form"

method

="post"

>

2324

<

input

type

="hidden"

name

="max_file_size"

value

="30000"

/>

25上傳的檔案:

26<

input

type

="file"

name

="userfile"

/>

27<

hr/>

28<

input

type

="submit"

name

="sub_button"

value

="上傳檔案的提交按鈕"

php中上傳檔案

1,情景描述 我們在開發過程中,總是會用到上傳檔案,實際上上傳檔案乙個方法就可以搞定 2,方案 filedata files file 2,貼上上傳檔案的 filename filedata name move uploaded file filedata tmp name uploads file...

jsp中上傳檔案

1.建立jsp 頁面 form action uploadservlet method post enctype multipart form data 用 戶 名 input type text name username 上傳檔案 input type file name file br inp...

gitlab中上傳檔案

cd到你的本地專案根目錄下,執行git命令 git initgit add 如果想新增某個特定的檔案,只需把.換成特定的檔名即可 git commit m 注釋語句 後面的https鏈結位址換成你自己的倉庫url位址,也就是上面紅框中標出來的位址 git pull origin master敲回車後...