All Products
Search
Document Center

Object Storage Service:PHP example for uploading to Object Storage Service (OSS) with a signed header

Last Updated:Oct 09, 2026

Overview

The Object Storage Service (OSS) software development kit (SDK) provides features for signing, uploading, and downloading. In some cases, you may need to use an API to upload and download content using a signature. This topic provides a PHP example that uses the PutObject operation to perform a signed upload.

Note

Use the OSS SDK whenever possible. The code in this topic is provided only as an example of a signed upload. You must modify the code to meet your business requirements.

Details

The following sample code shows how to use the PutObject operation in PHP 5.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(); // Initialize the cURL handle. 
    curl_setopt($ch, CURLOPT_URL, $url); // Set the request URL.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); // Set the request method. 
    
    $headers = array(
    "Date:".$time,
    'Content-Type:application/json',
    "Authorization:OSS ".$accesskey.":".$signature
    );
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);// Set the HTTP headers.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);// Set the string to submit.
    $document = curl_exec($ch);// Execute the cURL session. 
    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;
?>

References

Adding a signature to the Header

Applies to

  • Object Storage Service (OSS)