Quantcast
Viewing latest article 2
Browse Latest Browse All 2

PHP で Amazon S3 のバケット名を検証

文字列が Amazon S3 のバケット名の命名規則に従っているかを検証する PHP の関数は下記のように記述します。

/**
 * Validate bucket name of Amazon S3.
 *
 * @param string $name
 * @return bool
 */
function validate_bucket_name($name) {
    // Bucket names must be at least 3 and no more than 63 characters long
    $length = strlen($name);
    if ($length < 3 || 63 < $length) {
        return false;
    }

    // Bucket names must not be formatted as an IP address (e.g., 192.168.5.4)
    $pattern = '/^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$/';
    if (preg_match($pattern, $name)) {
        return false;
    }

    // Bucket name must be a series of one or more labels separated by a period (.), where each label:
    // - Must start with a lowercase letter or a number
    // - Must end with a lowercase letter or a number
    // - Can contain lowercase letters, numbers and dashes
    $pattern = '/^[0-9a-z]([0-9a-z\\-]*[0-9a-z])?(\\.[0-9a-z]([0-9a-z\\-]*[0-9a-z])?)*$/';
    if (!preg_match($pattern, $name)) {
        return false;
    }

    return true;
}

この関数は、下記の PHP スクリプトでテストしました。

function check_bucket_name($name) {
    if (validate_bucket_name($name)) {
        echo $name . ' is valid!' . "\n";
    } else {
        echo $name . ' is invalid...' . "\n";
    }
}

echo '----- Valid Bucket Name -----' . "\n";
check_bucket_name('myawsbucket');
check_bucket_name('my.aws.bucket');
check_bucket_name('myawsbucket.1');

echo '----- Invalid Bucket Name -----' . "\n";
check_bucket_name('192.168.5.4');
check_bucket_name('.myawsbucket');
check_bucket_name('myawsbucket.');
check_bucket_name('my..examplebucket');

検証結果は下記のとおりです。

$ php test_validate_bucket_name.php
----- Valid Bucket Name -----
myawsbucket is valid!
my.aws.bucket is valid!
myawsbucket.1 is valid!
----- Invalid Bucket Name -----
192.168.5.4 is invalid...
.myawsbucket is invalid...
myawsbucket. is invalid...
my..examplebucket is invalid...
$

正規表現が怪しいので、間違いがあったら教えてください。

参考文献


Viewing latest article 2
Browse Latest Browse All 2

Trending Articles