php curl 上傳檔案

來源:互聯網
上載者:User
假設server端上傳檔案處理指令碼upload.php:
  1. print_r($_POST);
  2. print_r($_FILES);
複製代碼

1、使用 CURL 預設的方法

  1. //如果php檔案是utf8編碼,系統是GBK編碼,那麼就需要轉下編碼,要不然Php在系統中找不到這個檔案
  2. $file = realpath(mb_convert_encoding('測試圖片.JPG','GBK','utf8'));
  3. $file = realpath('temp.jpg'); //要上傳的檔案
  4. $fields['f'] = '@'.$file; // 前面加@符表示上傳圖片
  5. $ch =curl_init();
  6. curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
  7. curl_setopt($ch,CURLOPT_POST,true);
  8. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  9. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  10. $content = curl_exec($ch);
  11. echo $content;
複製代碼


2、 另類的做法,有時我們需要將動態產生的內容當做檔案上傳到遠程伺服器,卻又不想在本機伺服器中構建臨時檔案。這樣就有了這個另類的寫法

  1. $contents =<<< 'TEXT'
  2. 這裡是檔案內容,也可以是圖片二進位,圖片需要修改上傳檔案類型
  3. TEXT;
  4. $varname = 'my';//上傳到$_FILES數組中的 key
  5. $name = '3.txt';//檔案名稱
  6. $type = 'text/plain';//檔案類型
  7. $key = "$varname\"; filename=\"$name\r\nContent-Type: $type\r\n";
  8. $fields[$key] = $contents;
  9. $ch =curl_init();
  10. curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
  11. curl_setopt($ch,CURLOPT_POST,true);
  12. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  13. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  14. $content = curl_exec($ch);
  15. echo $content;
複製代碼

上傳檔案, php, curl
  • 聯繫我們

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