php中curl、fsockopen的應用

來源:互聯網
上載者:User

標籤:blog   http   io   ar   os   sp   for   on   檔案   

最近要用到通過post上傳檔案,網上盛傳的有curl的post提交和fsockopen,其中curl最簡單,於是從最簡單的說起。這是簡單的將一個變數post到另外一個頁面$url = ‘‘;$data = array(‘a‘=> ‘b‘);$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $data);$ret = curl_exec($ch);curl_close($ch);主要說下這個選項CURLOPT_RETURNTRANSFER:如果設定為true/1,則curl_exec的時候不會自動將請求網頁的內容輸出到螢幕,$ret為請求網頁的內容,如果設定為false/0,則curl_exec的時候會自動將請求網頁的內容輸出到螢幕,此時如果請求成功的話$ret的內容是1或者true。下面是上傳本地檔案的代碼,如果需要上傳遠程檔案,則先down到本地,然後刪掉即可(如有同學有別的辦法還請告知):$url = ‘‘;$file = ‘1.jpg‘;$field[‘uploadFile‘] = ‘@‘.$file;(uploadFile為接收端的name名)$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $field);$ret = curl_exec($ch);curl_close($ch);-------------------------------------------------------------------------------------這是fsockopen的辦法:        $uploadInfo = array(                ‘host‘=>‘‘,                ‘port‘=>‘80‘,                ‘url‘=>‘/upload.php‘        );        $fp = fsockopen($uploadInfo[‘host‘],$uploadInfo[‘port‘],$errno,$errstr);    $file = ‘1.jpg‘;                $content = file_get_contents($file);                $boundary = md5(time());                $out.="--".$boundary."\r\n";                $out.="Content-Disposition: form-data; name=\"uploadFile\"; filename=\"".$file."\"\r\n";                $out.="Content-Type: image/jpg\r\n\r\n";                $out.=$content."\r\n";                $out.="--".$boundary."\r\n";                 fwrite($fp,"POST ".$uploadInfo[‘url‘]." HTTP/1.1\r\n");                fwrite($fp,"Host:".$uploadInfo[‘host‘]."\r\n");                fwrite($fp,"Content-Type: multipart/form-data; boundary=".$boundary."\r\n");                fwrite($fp,"Content-length:".strlen($out)."\r\n\r\n");                fwrite($fp,$out);                while (!feof($fp)){                        $ret .= fgets($fp, 1024);                }                fclose($fp);                $ret = trim(strstr($ret, "\r\n\r\n"));                preg_match(‘/http:.*/‘, $ret, $match);                return $match[0];

 

php中curl、fsockopen的應用

聯繫我們

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