0

I am working on a project, now i need to rename a key using its prefix in s3 php sdk api. i couldn't find it, if any can help. Thanks

    function moveFile($oldPath,$newPath){
$oKey = $this->getKey($oldPath);
$nKey = $this->getKey($newPath);

try{
    // Copy an object.
    $this->o->copyObject(array(
        'Bucket'     => $this->bucket,
        'ACL' => 'public-read',
        'Key'        => $nKey,
        'CopySource' => "{$this->bucket}/{$oKey}"
    ));

    $this->deleteFile($oldPath);

} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
    return false;
}

}

  • the code is the function that is working for me to move a folder/key based on prefix. but i am wondering if there is any function to rename a folder? like this? – faisal manzoor Jun 29 '17 at 03:41
  • Possible duplicate of [How to rename files and folder in Amazon S3?](https://stackoverflow.com/questions/21184720/how-to-rename-files-and-folder-in-amazon-s3) – LuFFy Jun 29 '17 at 04:48

3 Answers3

1

You can rename s3 files using below code :

$s3sdk = new Sdk($awsConfig);
$s3 = $s3sdk->createS3();
$s3->registerStreamWrapper();
rename($oldName, $newName);

both names need to contain the full s3 path e.g:

"s3://yourBucketName/path/to/file"

Basically registerStreamWrapper() enables PHP filesystem commands for s3 files.

LuFFy
  • 8,799
  • 10
  • 41
  • 59
1

I did this, you guys answered late. i did it myself but LuFFy answer is also correct.

function renameFolder($oldPath,$newPath){
$oKey = $this->getKey($oldPath);
if(strpos($oKey,'/')==false){$oKey.='/';}
//echo '<br>oKey: '.$oKey.'<br>'; 
try{
    // Copy an object.
    /*$this->o->copyObject(array(
        'Bucket'     => $this->bucket,
        'ACL' => 'public-read',
        'Key'        => $nKey,
        'CopySource' => "{$this->bucket}/{$oKey}"
    ));*/

    $result = $this->o->listObjects([
        'Bucket' => $this->bucket, // REQUIRED
        'Prefix' => $oKey,
    ]); 

    foreach($result['Contents'] as $file){
        //echo '<br>objectKey: '.$file['Key'].'<br>';
        $nKey = str_replace($this->getLastKey($oldPath),$this->getLastKey($newPath),$file['Key']);
        //echo '<br>nKey: '.$nKey.'<br>';
        $this->o->copyObject(array(
            'Bucket'     => $this->bucket,
            'ACL' => 'public-read',
            'Key'        => $nKey,
            'CopySource' => "{$this->bucket}/".$file['Key'].""
        ));
    }

    $this->deleteDir($oldPath);

}catch(S3Exception $e) {
    echo $e->getMessage() . "\n";
    return false;
}

}

0

I have managed to rename existing files on the batch using below steps:

  1. Lets say your config/filesystems.php looks like this:
    'disks' => [
      's3_test_bucket' => [
            'driver' => 's3',
            'key'    => env('AWS_KEY', 'your_aws_key_here'),
            'secret' => env('AWS_SECRET','your_aws_secret_here'),
            'region' =>  env('AWS_REGION', 'your_aws_region_here'),
            'version' => 'latest',
            'bucket'  => 'my-test-bucket',
      ],
    ];
  1. Let's say, you have my-test-bucket on your AWS S3.
  2. Lets say you have following files inside the my-test-bucket/test-directory directory. i.e.

    • test-files-1.csv
    • test-files-2.csv
    • test-files-3.csv
  3. Call below function to rename existing files on a selected directory on S3 Bucket.

    $directoryPath = 'test-directory';
    $storage = new MyStorageRepository();
    $storage->renameAnyExistingFilesOnImportDirectory('my-test-bucket', 'test-directory');
  1. Output: files should be rename as below on my-test-bucket/test-directory directory:

    • test-files-1--1548870936.csv
    • test-files-2--1548870936.csv
    • test-files-3--1548870936.csv
  2. Include the below library class or methods on your class and you should be good.

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;

class MyStorageRepository
{
    public function renameAnyExistingFilesOnImportDirectory($bucket, $directoryPath)
    {
        $directoryPath = App::environment() . '/' . $directoryPath;
        $storage = Storage::disk('s3_test_bucket');

        $suffix = '--' . time(); // File suffix to rename.

        if ($storage->exists($directoryPath)) {
            $this->renameStorageDirectoryFiles($directoryPath, $storage, $suffix);
        }
    }

    private function getNewFilename($filename, $suffix = null)
    {
        $file = (object) pathinfo($filename);

        if (!$suffix) {
            $suffix = '--' . time();
        }

        return $file->dirname . '/' . $file->filename . $suffix . '.' . $file->extension;
    }

    private function renameStorageDirectoryFiles($directoryPath, $storage = null, $suffix = null, $filesystemDriver = null)
    {
        if (!$storage) {
            $storage = Storage::disk($filesystemDriver);
        }

        // List all the existing files from the directory
        $files = $storage->files($directoryPath);

        if (count($files) < 1 ) return false;

        foreach($files as $file) {
            // Get new filename
            $newFilename = Helpers::getNewFilename($file, $suffix);

            // Renamed the files
            $storage->move($file, $newFilename);
        }
    }
}
rc.adhikari
  • 1,974
  • 1
  • 21
  • 24