PHP curl put方式上传文件

发送端:

<?php

function curlPut($destUrl, $sourceFileDir, $headerArr = array(), $timeout = 10)
{
    $ch = curl_init(); //初始化curl
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而不直接输出
    curl_setopt($ch, CURLOPT_URL, $destUrl); //设置put到的url
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证对等证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //不检查服务器SSL证书

    curl_setopt($ch, CURLOPT_PUT, true); //设置为PUT请求
    curl_setopt($ch, CURLOPT_INFILE, fopen($sourceFileDir, 'rb')); //设置资源句柄
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($sourceFileDir));

    $response = curl_exec($ch);
    if ($error = curl_error($ch))
    {
        $bkArr =  array(
            'code' => 0,
            'msg' => $error,
        );
    }
    else
    {
        $bkArr =  array(
            'code' => 1,
            'msg' => 'ok',
            'resp' => $response,
        );
    }

    curl_close($ch); // 关闭 cURL 释放资源

    return $bkArr;
}

$destUrl = 'http://www.songjm.com/http_put_save.php';
$sourceFileDir = 'asset/pic.png';
$headerArr = array(
    'filename:newname.png',
);

$bkJson = curlPut($destUrl, $sourceFileDir, $headerArr);
$bkArr = json_decode($bkJson, true);
echo "<pre>";
print_r($bkArr);
die;

接收端:

<?php

if ($_SERVER['REQUEST_METHOD'] != 'PUT')
{
    $bkMsg = array(
        'code' => -1,
        'msg' => 'not put',
    );
    echo json_encode($bkMsg);
    exit();
}

$filename = $_SERVER['HTTP_FILENAME'];

$fileSaveDir = 'upload/';
$newFile = $fileSaveDir.$filename;

$handleToSave = fopen($newFile,'wb+'); 
$handleSource = fopen('php://input','rb');

while (!feof($handleSource))
{
    fwrite($handleToSave, fread($handleSource, 1024));
}

fclose($handleToSave);
fclose($handleSource);

$bkMsg = array(
    'code' => 1,
    'msg' => 'ok',
);
echo json_encode($bkMsg);
exit();

转自 https://www.cnblogs.com/songjianming/archive/2019/06/23/11072958.html

原文地址:https://www.cnblogs.com/rxbook/p/11227964.html