Created
December 18, 2013 07:55
-
-
Save ericsk/8018784 to your computer and use it in GitHub Desktop.
產生 SAS 存取非公開的 Blob 資料
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 轉換時間 | |
| function isoDate($timestamp = null) { | |
| $tz = @date_default_timezone_get(); | |
| @date_default_timezone_set('UTC'); | |
| if (is_null($timestamp)) { | |
| $timestamp = time(); | |
| } | |
| $returnValue = str_replace('+00:00', '.0000000Z', @date('c', $timestamp)); | |
| @date_default_timezone_set($tz); | |
| return $returnValue; | |
| } | |
| # 產生 SAS | |
| function createSignature($accountName, $accountKey, $path, $start, $expires) { | |
| $res = "/$accountName$path"; | |
| $strToSign = array(); | |
| $strToSign[] = 'r'; // 權限, 純讀取 | |
| $strToSign[] = $start; | |
| $strToSign[] = $expires; | |
| $strToSign[] = $res; | |
| $sig = base64_encode( | |
| hash_hmac('sha256', | |
| implode('\n', $strToSign), | |
| $accountKey, | |
| true)); | |
| return $sig; | |
| } | |
| # .... | |
| $baseUrl = "https://ericishandsome.blob.core.windows.net/dl"; | |
| $resourceName = "/foo.pdf"; | |
| # 設定 SAS 的時效 | |
| $start = isoDate(time()); | |
| $expires = isoDate(time() + 3600); # 1小時後 | |
| # 產生 SAS | |
| $sig = createSignature($accountName, $accountKey, $path, $start, $expires); | |
| # 產生可存取 URL 的 query string | |
| $params = array(); | |
| $params[] = 'st=' . urlencode($start); | |
| $params[] = 'se=' . urlencode($expires); | |
| $params[] = 'sr=b'; // 'b' for blob | |
| $params[] = 'sp=r'; // read | |
| $params[] = 'sig=' . urlencode($sig); | |
| # 組合成可存取的 URL | |
| # 大概會長成 https://ericishandsome.blob.core.windows.net/dl/foo.pdf?st=....&se=....&sr=b&sp=r&sig=...... 這樣 | |
| $url = "$baseUrl$resourceName?" . implode('&', $params); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment