1

我编写了以下函数来编码我的 S3 链接,以便它们处理亚马逊的 S3 编码系统来保护链接。问题是它只有在文件在存储桶中时才有效。如果我在存储桶中创建一个子文件夹并将文件粘贴在那里,它就不起作用。我究竟做错了什么?

function encodeS3($sURL,$sAccessKey,$sSecretKey,$nExpireMinutes = 5) {
  $sFile = basename($sURL);
  $sBucket = basename(str_replace('/' . $sFile,'',$sURL));
  $asQuery = array(
    'AWSAccessKeyId' => $sAccessKey,
  );
  $nExpireSecs = absint( $nExpireMinutes ) * 60;
  $nExpireSecs = time() + absint( $nExpireSecs );
  $asQuery[ 'Expires' ] = $nExpireSecs;
  $sAmazonText = "GET\n\n\n{$nExpireSecs}\n/{$sBucket}/{$sFile}";
  $asQuery[ 'Signature' ] = urlencode( base64_encode( ( hash_hmac( 'sha1', utf8_encode( $sAmazonText ), $sSecretKey, TRUE ) ) ) );
  $s = add_query_arg( $asQuery, "https://s3.amazonaws.com/{$sBucket}/{$sFile}" );
  return esc_url($s);
}
4

1 回答 1

0

我只需要更改解析 URL 的方式。

function encodeS3($sURL,$sAccessKey,$sSecretKey,$nExpireMinutes = 5) {
  /*
  $sFile = basename($sURL);
  $sBucket = basename(str_replace('/' . $sFile,'',$sURL));
  */
  $sURL = str_replace('https://','',$sURL);
  $sURL = str_replace('http://','',$sURL);
  $sURL = str_replace(urlencode('https://'),'',$sURL);
  $sURL = str_replace(urlencode('http://'),'',$sURL);
  $asParts = explode('/',$sURL);
  array_shift($asParts);
  $sBucket = array_shift($asParts);
  $sFile = implode('/',$asParts);

  $asQuery = array(
    'AWSAccessKeyId' => $sAccessKey,
  );
  $nExpireSecs = absint( $nExpireMinutes ) * 60;
  $nExpireSecs = time() + absint( $nExpireSecs );
  $asQuery[ 'Expires' ] = $nExpireSecs;
  $sAmazonText = "GET\n\n\n{$nExpireSecs}\n/{$sBucket}/{$sFile}";
  $asQuery[ 'Signature' ] = urlencode( base64_encode( ( hash_hmac( 'sha1', utf8_encode( $sAmazonText ), $sSecretKey, TRUE ) ) ) );
  $s = add_query_arg( $asQuery, "https://s3.amazonaws.com/{$sBucket}/{$sFile}" );
  return esc_url($s);
}

顺便说一句,上面使用了一些仅在 WordPress 中可用的功能。如果您需要直接的 PHP,则必须对其进行调整。

于 2012-08-30T09:09:08.020 回答