LoginSignup
1
1

More than 3 years have passed since last update.

StaticPress S3のスクリプトをAWS SDK for PHP3に対応させて書く

Posted at

急ですが、EC2上に構築しているWordPressの記事をHTMLに変換してS3のバケットに送るということをやりたくなりました。
StaticPressとStaticPress S3を試したのですが、ファイルをS3に送るところだけ別でいろいろとしたいなぁ、と考えました。
(この記事に載せるには「いろいろ」は大人の事情でかけません…。なので、バージョン上げた部分だけ書きます)

ファイルをS3に送信するスクリプトは「StaticPress S3」のドキュメントにて公開されていました。
http://ja.staticpress.net/2013/06/11/69/
現在は2019年なので、内容が古いです。
AWS SDK for PHPのバージョンが2の時の内容ですね。

現在はAWS SDK for PHPはバージョン3になってます。
https://aws.amazon.com/jp/sdk-for-php/
なので、このスクリプトを3を使って書き直してみました。
PHP7.3
AWS SDK for PHPはpharで落としてきて読み込んでいます。

<?php
require_once('aws.phar');
use Aws\S3\S3Client;  
use Aws\Exception\AwsException;
use Aws\Credentials\Credentials;

$key = 'Your Access Key';
$secret = 'Your Secret Key';
$region = 'ap-northeast-1'; 
$bucket = 'bucket_name';
$dir = '/var/www/html/fugafuga/';

/**
 * 指定されたディレクトリのファイル一覧を取得
 */
function get_dir_file_list($dir)
{
    $check_dirs = [$dir];
    $file_paths = [];
    $file_name = [];

    while( $check_dirs ) 
    {
        $dir_path = $check_dirs[0] ;

        if( is_dir ( $dir_path ) && $handle = opendir ( $dir_path ) ) 
        {
            while( ( $file = readdir ( $handle ) ) !== false ) 
            {
                if( in_array ( $file, [ ".", ".." ] ) !== false ) 
                {
                    continue;
                } 

                $path = rtrim ( $dir_path, "/" ) . "/" . $file ;

                if ( filetype ( $path ) === "dir" ) 
                {
                    $check_dirs[] = $path ;
                } 
                else 
                {
                    $file_name[] = $path;
                }
            }
        }
        array_shift( $check_dirs ) ;
    }

    return $file_name;
}

/**
 * ここから実際の処理
 */
try 
{
    $credentials = new Credentials($key, $secret);
    // Create a S3Client
    $s3Client = new S3Client([
        'region' => $region,
        'version' => 'latest',
        'credentials' => $credentials,
    ]);

    $files = get_dir_file_list($dir);
    $info = new Finfo(FILEINFO_MIME_TYPE);
    foreach ($files as $filename) 
    {
        $filetype = $info->file($filename);
        $filebody = fopen($filename, 'r');
        if ( $filetype == 'text/plain') 
        {
            if (preg_match('/\.css$/i', $filename)) 
            {
                $filetype = 'text/css';
            } 
            else if(preg_match('/\.js$/i', $filename)) 
            {
                $filetype = 'application/x-javascript';
            } 
            else if(preg_match('/\.html?$/i', $filename)) 
            {
                $filetype = 'text/html';
            }
            else if(preg_match('/\.xml$/i', $filename)) 
            {
                $filetype = 'application/xml';
            }
        }

        echo $filetype . ':' . str_replace($dir, '', $filename) . "\n";

        $response = $s3Client->putObject([
            'Bucket' => $bucket,
            'Key' => str_replace($dir, '', $filename),
            'Body' => $filebody,
            'ContentType' => $filetype,
//          'StorageClass' => 'STANDARD',
//          'ACL' => 'public-read',
        ]);

    }
} catch(S3Exception $e) {
    echo $e->getMessage();
}

ディレクトリ下のファイルを取得する関数を書き直しました。
拡張子である程度しぼって取得するほうがよかったかもなぁ、とも思います。ContentTypeも決めているので…。

コメントにしてあるStorageClassとACLは必須パラメータではないです。

APIドキュメントはこちらを。
https://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1