OSS签名Header实现Demo(PHP)

概述

OSS的集成上传和下载提供了SDK可以直接使用,但实际使用中一些用户受限环境或者设备限制需要使用api方式来实现上传和下载,本文以PutObject接口为例,提供了PHP实现的demo。
注:建议优先使用OSS提供SDK,本文提供的只是签名实现上传demo,实际使用中需要结合业务来进行改动代码

详细信息

PutObject实现Demo(测试环境php5.6.30):

<?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;
?>
上一篇:使用Docker Compose部署基于Sentinel的高可用Redis集群


下一篇:Hive on Spark安装配置详解