PHP傳統檔案上傳和Base64位檔案上傳

來源:互聯網
上載者:User

一、基本知識

通過使用 PHP 的全域數組 $_FILES,你可以從客戶電腦向遠程伺服器上傳檔案。

第一個參數是表單的 input name,第二個下標可以是 "name", "type", "size", "tmp_name" 或 "error"。就像這樣:

$_FILES["file"]["name"] - 被上傳檔案的名稱

$_FILES["file"]["type"] - 被上傳檔案的類型

$_FILES["file"]["size"] - 被上傳檔案的大小,以位元組計

$_FILES["file"]["tmp_name"] - 儲存在伺服器的檔案的臨時副本的名稱

$_FILES["file"]["error"] - 由檔案上傳導致的錯誤碼

這是一種非常簡單檔案上傳方式。基於安全方面的考慮,您應當增加有關什麼使用者有權上傳檔案的限制。

二、常用上傳

  1. if ((($_FILES["file"]["type"] == "image/gif")
  2. || ($_FILES["file"]["type"] == "image/jpeg")
  3. || ($_FILES["file"]["type"] == "image/pjpeg"))
  4. && ($_FILES["file"]["size"] < 20000))
  5. {
  6. if ($_FILES["file"]["error"] > 0)
  7. {
  8. echo "Return Code: " . $_FILES["file"]["error"] . "
    ";
  9. }
  10. else
  11. {
  12. echo "Upload: " . $_FILES["file"]["name"] . "
    ";
  13. echo "Type: " . $_FILES["file"]["type"] . "
    ";
  14. echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
    ";
  15. echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
    ";
  16. if (file_exists("upload/" . $_FILES["file"]["name"]))
  17. {
  18. echo $_FILES["file"]["name"] . " already exists. ";
  19. }
  20. else
  21. {
  22. move_uploaded_file($_FILES["file"]["tmp_name"],
  23. "upload/" . $_FILES["file"]["name"]);
  24. echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  25. }
  26. }
  27. }
  28. else
  29. {
  30. echo "Invalid file";
  31. }
  32. ?>
複製代碼

三、php讀取和儲存base64編碼的圖片內容

  1. if($_POST['submit']){
  2. $image_info = getimagesize($_FILES['file']['tmp_name']);//$_FILES['file']['tmp_name']即檔案路徑
  3. $base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
  4. echo $base64_image_content;die;
  5. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
  6. $type = $result[2];
  7. $new_file = "./test.{$type}";
  8. if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
  9. echo '新檔案儲存成功:', $new_file;
  10. }
  11. }
  12. }
  13. ?>
複製代碼


檔案上傳, PHP
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.