PHP利用CURL方法類比POST提交資料並獲得傳回值的小細節

來源:互聯網
上載者:User

背景:我與同事之間互相調用API,進行資料處理,並返回處理結果

互動:我傳遞一個圖片資訊過去,他那邊給我返回一個識別映像結果的json對象。

方法:使用php的內建curl函數

詳情:

   一.開啟擴充服務:開啟php.ini檔案,把 “;extension=php_curl.dll”  前面的;去掉並重啟apache

    二.實現代碼:$filePath = '@C:/Program Files (x86)/EasyPHP/data/localweb/SmartCampus/Public/Uploads/bindimages' . "/" . $date . "/" . $photo;
                            $postUrl = 'http://localhost/SmartCampus/AddImagesUpload.php';

                            // 1. 初始化
                            $ch = curl_init();
                            //post發送的參數數組
                            $postData = array(
                                //'loginfield' => 'username',
                                //'username' => 'ybb',
                                //'password' => '123456',
                                'file' => $filePath
                            );
                            // 2. 設定選項,包括URL
                            curl_setopt($ch, CURLOPT_HEADER, false);
//啟用時會發送一個常規的POST請求,類型為:application/x-www-form-urlencoded,就像表單提交的一樣。
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                           // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                           // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                            curl_setopt($ch, CURLOPT_URL, $postUrl);


                            // 3. 執行並擷取HTML文檔內容
                            $output = curl_exec($ch);
                            //擷取各種運行中資訊,便於調試    
                            $curlInfo = curl_getinfo($ch);
                            // 4. 釋放curl控制代碼
                            curl_close($ch);
                            $res=json_decode($output,true);

    三.注意:

      1.json_decode()函數的第二個參數為true時,返回解碼後的數組,不是解碼後的對象

      2.加橫線部分的CURL設定似乎有順序要求,如需擷取CURL傳回值 需把“ curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);”這兩行放在前面,放在後面則返回bool值。

聯繫我們

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