对象存储OSS使用PHP语言实现签名Header上传的示例

作者: siediyer 分类: PHP 发布时间: 2024-03-26 16:04

PHP 5.6.30版本使用PutObject接口实现示例代码如下。

<?php 
function curlput($url,$data,$method='PUT',$bucket,$object,$accesskey ,$accesskeySecret){
 $time = gmdate ("D, d M Y H:i:s T");
    $str = "PUT\n\n"."application/json\n".$time."\n/".$bucket."/".$object;
    //echo($str);
    $signature = base64_encode(hash_hmac("sha1", $str, $accesskeySecret, true));
    //echo($time);
    //echo($signature);
    $ch = curl_init(); //初始化CURL句柄 
    curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式 
    
    $headers = array(
    "Date:".$time,
    'Content-Type:application/json',
    "Authorization:OSS ".$accesskey.":".$signature
    );
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);//设置HTTP头信息
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
    $document = curl_exec($ch);//执行预定义的CURL 
    if(!curl_errno($ch)){ 
      $info = curl_getinfo($ch); 
      echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; 
    } else { 
      echo 'Curl error: ' . curl_error($ch); 
    }
    curl_close($ch);
     
    return $document;
}

$accesskey ='xxx';
$accesskeySecret ='xxx';
$bucket = 'bucketname';
$object = 'mytest/2.txt';
$url = 'http://bucketname.oss-cn-hangzhou.aliyuncs.com/mytest/2.txt';
$data = "{wewwe:wewee}";
$return = curlput($url, $data, 'PUT',$bucket,$object,$accesskey,$accesskeySecret);
 
var_dump($return);
exit;
?>

https://help.aliyun.com/zh/oss/example-of-uploading-signature-headers-using-php-in-object-storage-service#e9e6a297c3nam

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

Title - Artist
0:00