curl命令類比表單上傳檔案

來源:互聯網
上載者:User
  1. //初始化

  2. $ch = curl_init();

  3. // 要上傳的本地檔案地址"@F:/xampp/php/php.ini"上傳時候,上傳路徑前面要有@符號

  4. $furl = "@F:/xampp/php/php.ini";
  5. $post_data = array (
  6. "upload" => $furl
  7. );

  8. //CURLOPT_URL 是指提交到哪裡?相當於表單裡的“action”指定的路徑

  9. $url = "http://localhost/test/curl/curl_post.php";

  10. //設定變數

  11. curl_setopt($ch, CURLOPT_URL, $url);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);//執行結果是否被返回,0是返回,1是不返回
  13. curl_setopt($ch, CURLOPT_HEADER, 0);//參數設定,是否顯示頭部資訊,1為顯示,0為不顯示

  14. //偽造網頁來源地址,偽造來自百度的表單提交

  15. curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com");

  16. //表單資料,是正規的表單設定值為非0

  17. curl_setopt($ch, CURLOPT_POST, 1);

  18. curl_setopt($ch, CURLOPT_TIMEOUT, 1);//設定curl執行逾時時間最大是多少

  19. //使用數組提供post資料時,CURL組件大概是為了相容@filename這種上傳檔案的寫法,

  20. //預設把content_type設為了multipart/form-data。雖然對於大多數web伺服器並
  21. //沒有影響,但是還是有少部分伺服器不相容。本文得出的結論是,在沒有需要上傳檔案的
  22. //情況下,盡量對post提交的資料進行http_build_query,然後發送出去,能實現更好的相容性,更小的請求資料包。
  23. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

  24. //執行並擷取結果

  25. $output = curl_exec($ch);
  26. if($outopt === FALSE)
  27. {
  28. echo "
    ","cUrl Error:".curl_error($ch);
  29. }
  30. // 釋放cURL控制代碼
  31. curl_close($ch);
  32. ?>

複製代碼

檔案2:curl_post.php

  1. echo "
    ";
  2. var_dump($_FILES);
  3. ?>
複製代碼

結果如下:

  1. array(1) {
  2. ["upload"]=>
  3. array(5) {
  4. ["name"]=>
  5. string(7) "php.ini"
  6. ["type"]=>
  7. string(24) "application/octet-stream"
  8. ["tmp_name"]=>
  9. string(24) "F:xampptmpphpB2D1.tmp"
  10. ["error"]=>
  11. int(0)
  12. ["size"]=>
  13. int(46217)
  14. }
  15. }
複製代碼
  • 聯繫我們

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