zoukankan      html  css  js  c++  java
  • curl put方式上传文件

    发送端

     1 <?php
     2 
     3 function curlPut($destUrl, $sourceFileDir, $headerArr = array(), $timeout = 10)
     4 {
     5     $ch = curl_init(); //初始化curl
     6     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而不直接输出
     7     curl_setopt($ch, CURLOPT_URL, $destUrl); //设置put到的url
     8     curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
     9     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    10     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证对等证书
    11     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //不检查服务器SSL证书
    12 
    13     curl_setopt($ch, CURLOPT_PUT, true); //设置为PUT请求
    14     curl_setopt($ch, CURLOPT_INFILE, fopen($sourceFileDir, 'rb')); //设置资源句柄
    15     curl_setopt($ch, CURLOPT_INFILESIZE, filesize($sourceFileDir));
    16 
    17     $response = curl_exec($ch);
    18     if ($error = curl_error($ch))
    19     {
    20         $bkArr =  array(
    21             'code' => 0,
    22             'msg' => $error,
    23         );
    24     }
    25     else
    26     {
    27         $bkArr =  array(
    28             'code' => 1,
    29             'msg' => 'ok',
    30             'resp' => $response,
    31         );
    32     }
    33 
    34     curl_close($ch); // 关闭 cURL 释放资源
    35 
    36     return $bkArr;
    37 }
    38 
    39 $destUrl = 'http://www.songjm.com/http_put_save.php';
    40 $sourceFileDir = 'asset/pic.png';
    41 $headerArr = array(
    42     'filename:newname.png',
    43 );
    44 
    45 $bkJson = curlPut($destUrl, $sourceFileDir, $headerArr);
    46 $bkArr = json_decode($bkJson, true);
    47 echo "<pre>";
    48 print_r($bkArr);
    49 die;

    接收端

     1 <?php
     2 
     3 if ($_SERVER['REQUEST_METHOD'] != 'PUT')
     4 {
     5     $bkMsg = array(
     6         'code' => -1,
     7         'msg' => 'not put',
     8     );
     9     echo json_encode($bkMsg);
    10     exit();
    11 }
    12 
    13 $filename = $_SERVER['HTTP_FILENAME'];
    14 
    15 $fileSaveDir = 'upload/';
    16 $newFile = $fileSaveDir.$filename;
    17 
    18 $handleToSave = fopen($newFile,'wb+'); 
    19 $handleSource = fopen('php://input','rb');
    20 
    21 while (!feof($handleSource))
    22 {
    23     fwrite($handleToSave, fread($handleSource, 1024));
    24 }
    25 
    26 fclose($handleToSave);
    27 fclose($handleSource);
    28 
    29 $bkMsg = array(
    30     'code' => 1,
    31     'msg' => 'ok',
    32 );
    33 echo json_encode($bkMsg);
    34 exit();
  • 相关阅读:
    UVa 1252 20个问题
    HDU 2196 Computer
    HDU 1520 Anniversary party
    HDU 2066 一个人的旅行
    UVa 10048 噪音恐惧症(Floyd)
    UVa 247 电话圈(Floyd传递闭包)
    HDU 2544 最短路(Dijkstra)
    HDU 1548 A strange lift (Dijkstra)
    UVa 1151 买还是建
    UVa 1395 苗条的生成树(Kruskal+并查集)
  • 原文地址:https://www.cnblogs.com/songjianming/p/11072958.html
Copyright © 2011-2022 走看看