php curl 發送get或者post請求

來源:互聯網
上載者:User

標籤:php   post   get   curl   發送請求   

php可以扮演資料的寄件者。

  1. 簡單的get

$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "http://SomeDomain/SamplePath?SomeVar=test");curl_exec($ch);curl_close($ch);


2.  簡單的post

$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "http://SomeDomain/SamplePath");curl_setopt($ch, CURLOPT_POST, true); // 啟用POSTcurl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array( "a"=>"123", "b"=>"321") )); curl_exec($ch); curl_close($ch);


3. 進階的post,可設定多個參數

$toURL = "http://SomeDomain/SamplePath?SomeVar=XX";$post = array(  "a"=>"123",  "b"=>"321",);$ch = curl_init();$options = array(  CURLOPT_URL=>$toURL,  CURLOPT_HEADER=>0,  CURLOPT_VERBOSE=>0,  CURLOPT_RETURNTRANSFER=>true,  CURLOPT_USERAGENT=>"Mozilla/4.0 (compatible;)",  CURLOPT_POST=>true,  CURLOPT_POSTFIELDS=>http_build_query($post),);curl_setopt_array($ch, $options);// CURLOPT_RETURNTRANSFER=true 會返回伺服器響應代碼,// false 時只返回成功與否;$result = curl_exec($ch); curl_close($ch);echo $result;


4. post 傳送檔案


發送端代碼:

$target_url = ‘http://127.0.0.1/accept.php‘;        //This needs to be the full path to the file you want to send.$file_name_with_full_path = realpath(‘./sample.jpeg‘);        /* curl will accept an array here too.         * Many examples I found showed a url-encoded string instead.         * Take note that the ‘key‘ in the array will be the key that shows up in the         * $_FILES array of the accept script. and the at sign ‘@‘ is required before the         * file name.         */$post = array(‘extra_info‘ => ‘123456‘,‘file_contents‘=>‘@‘.$file_name_with_full_path);         $ch = curl_init();curl_setopt($ch, CURLOPT_URL,$target_url);curl_setopt($ch, CURLOPT_POST,1);curl_setopt($ch, CURLOPT_POSTFIELDS, $post);        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);$result=curl_exec ($ch);curl_close ($ch);echo $result;


接收端代碼:

$uploaddir = realpath(‘./‘) . ‘/‘;$uploadfile = $uploaddir . basename($_FILES[‘file_contents‘][‘name‘]);echo ‘<pre>‘;if (move_uploaded_file($_FILES[‘file_contents‘][‘tmp_name‘], $uploadfile)) {    echo "File is valid, and was successfully uploaded.\n";} else {    echo "Possible file upload attack!\n";}echo ‘Here is some more debugging info:‘;print_r($_FILES);echo "\n<hr />\n";print_r($_POST);print "</pr" . "e>\n";


本文出自 “安家圈子交流學習” 部落格,請務必保留此出處http://brucetam.blog.51cto.com/1863614/1433671

聯繫我們

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