中央論壇 - CENTER BBS

標題: [PHP]用Curl上傳文件教學 - curl_init() [打印本頁]

作者: 郭子錢    時間: 2013-8-27 15:17
標題: [PHP]用Curl上傳文件教學 - curl_init()
上傳文件和POST十分相似。因為所有的文件上傳表單都是通過POST方法提交的。

(基礎閱讀:如何使用PHP CURL,基礎教學。)

首先新建一個接收文件的頁面,命名為 upload_output.php:
  1. print_r($_FILES);
複製代碼
以下是真正執行文件上傳任務的腳本:

  1. $url = "http://localhost/upload_output.php";
  2. $post_data = array (
  3.     "foo" => "bar",
  4.     // 要上傳的本地文件地址
  5.     "upload" => "@C:/wamp/www/test.zip"
  6. );
  7. $ch = curl_init();
  8. curl_setopt($ch, CURLOPT_URL, $url);
  9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  10. curl_setopt($ch, CURLOPT_POST, 1);
  11. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  12. $output = curl_exec($ch);
  13. curl_close($ch);
  14. echo $output;
複製代碼
如果你需要上傳一個文件,只需要把文件路徑像一個post變量一樣傳過去,不過記得在前面加上@符號。執行這段腳本應該會得到如下輸出:
  1. Array (
  2. [upload] => Array
  3. (
  4. [name] => Note.txt
  5. [type] => text/plain
  6. [tmp_name] => C:\WINDOWS\TEMP\php7B8.tmp
  7. [error] => 0
  8. [size] => 0
  9. )
  10. )
複製代碼





歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/) Powered by Discuz! X3