Git Product home page Git Product logo

amazon-s3-php-class's Introduction

Amazon S3 PHP Class

Usage

OO method (e,g; $s3->getObject(...)):

$s3 = new S3($awsAccessKey, $awsSecretKey);

Statically (e,g; S3::getObject(...)):

S3::setAuth($awsAccessKey, $awsSecretKey);

Object Operations

Uploading objects

Put an object from a file:

S3::putObject(S3::inputFile($file, false), $bucketName, $uploadName, S3::ACL_PUBLIC_READ)

Put an object from a string and set its Content-Type:

S3::putObject($string, $bucketName, $uploadName, S3::ACL_PUBLIC_READ, array(), array('Content-Type' => 'text/plain'))

Put an object from a resource (buffer/file size is required - note: the resource will be fclose()'d automatically):

S3::putObject(S3::inputResource(fopen($file, 'rb'), filesize($file)), $bucketName, $uploadName, S3::ACL_PUBLIC_READ)

Retrieving objects

Get an object:

S3::getObject($bucketName, $uploadName)

Save an object to file:

S3::getObject($bucketName, $uploadName, $saveName)

Save an object to a resource of any type:

S3::getObject($bucketName, $uploadName, fopen('savefile.txt', 'wb'))

Copying and deleting objects

Copy an object:

S3::copyObject($srcBucket, $srcName, $bucketName, $saveName, $metaHeaders = array(), $requestHeaders = array())

Delete an object:

S3::deleteObject($bucketName, $uploadName)

Bucket Operations

Get a list of buckets:

S3::listBuckets()  // Simple bucket list
S3::listBuckets(true)  // Detailed bucket list

Create a bucket:

S3::putBucket($bucketName)

Get the contents of a bucket:

S3::getBucket($bucketName)

Delete an empty bucket:

S3::deleteBucket($bucketName)

amazon-s3-php-class's People

Contributors

ad-m avatar binki avatar clphillips avatar damac23 avatar daveajones avatar dropfan avatar ericnorris avatar gabrieljenik avatar lucatacconi avatar ptarjan avatar racklin avatar stristr avatar tmuras avatar tpyo avatar vrana avatar zyberspace avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

amazon-s3-php-class's Issues

Error when I use the samples.

Hi guys I'm using the Amazon S3 PHP Class version 0.5.x but I change the accesskey and secret key.
And show againg and again this error.

ERROR: AWS access information required Please edit the following lines in this file: define('awsAccessKey'

I change all say "chage-me" but the error show again. I need anything special?

I'm using a shared hosting for php scripts.

I test a sample from http://net.tutsplus.com/tutorials/php/how-to-use-amazon-s3-php-to-dynamically-store-and-manage-files-with-ease/comment-page-1/#comments with S3.php version 0.2.3 and work fine for list and upload files.

Tagged release

Hi

Do you plan to create a tagged release? We prefer to pull from a tagged release for all production builds.

error while uploading a file

i can upload below 900kb video file but if i am try to upload 2 or 7 mb, then i'm getting error

A PHP Error was encountered
Severity: User Warning
Message: S3::inputFile(): Unable to open input file:
Filename: views/S3.php
Line Number: 355

streaming

is there streaming possibility coming to this class ?

Cloudfront CDN not working

Created a distribution using the createdistribution function.

When accessing the URL using the domain value it gives an error which says "Missing Key-Pair-Id query parameter"

restoreObject

This class doesn't have a method for restoring an object from glacier so I made one. Feel free to use or modify. One note, besides the code below, you'll also need to change the S3Request class getResponse function.

Change this:
if (array_key_exists('acl', $this->parameters) ||
array_key_exists('location', $this->parameters) ||
array_key_exists('torrent', $this->parameters) ||
array_key_exists('website', $this->parameters) ||
array_key_exists('logging', $this->parameters))
$this->resource .= $query;
to this:
if (array_key_exists('acl', $this->parameters) ||
array_key_exists('location', $this->parameters) ||
array_key_exists('torrent', $this->parameters) ||
array_key_exists('website', $this->parameters) ||
array_key_exists('logging', $this->parameters) ||
array_key_exists('restore', $this->parameters))
$this->resource .= $query;

Sorry if this is in the wrong spot. I couldn't figure out how to do a commit.

/**
* Restore object from GLACIER
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param int $daysToRestoreFor Number of days you want file to stay on S3 storage before it gets deleted keeping only the GLACIER version
* @param boolean $returnCode Whether to return response code or a description of the result
* @return int | string
*/
public static function restoreObject($bucket, $uri, $daysToRestoreFor = 30, $returnCode = TRUE){
$responseCodeExplanations = array(409 => '409 RestoreAlreadyInProgress: Object restore is already in progress',
202 => '202 Accepted: file will be restored in the next 3-5 hours',
200 => '200 OK: Object already restored');

    $rest = new S3Request('POST', $bucket, $uri, self::$endpoint);

    $dom = new DOMDocument;
    $restoreRequest = $dom->createElement('RestoreRequest');
    $days = $dom->createElement('Days', $daysToRestoreFor);
    $restoreRequest->appendChild($days);
    $dom->appendChild($restoreRequest);
    $rest->data = $dom->saveXML();

    $rest->setParameter('restore', null);
    $rest->setHeader('Content-Type', 'application/xml');
    $rest->size = strlen($rest->data);

    if ($rest->response->error === false) $rest->getResponse();
    if($rest->response->error === false || $rest->response->code == 409){
        if(array_key_exists($rest->response->code, $responseCodeExplanations)){
            if($returnCode){
                return $rest->response->code;
            }
            else{
                return $responseCodeExplanations[$rest->response->code];
            }
        }
        else if ($rest->response->error === false)
            $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
    }
    else {
        self::__triggerError(sprintf("S3::restoreObject({$bucket}, {$uri}): [%s] %s",
        $rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
        return false;
    }
}

error while uploading a file

i ca upload below 900kb video files, but if i'm try to upload then getting error.

A PHP Error was encountered
Severity: User Warning
Message: S3::inputFile(): Unable to open input file:
Filename: views/S3.php
Line Number: 355

get content-type for object

First of all great class! So simple and easy to use!
Just one issue:
When I copy an object it looses its content type.
I figured I would get the content type, then pass it as a parameter to the copy function.
When I did:
$s3->getObjectInfo('bucket', 'inputFile');
or
$s3->getObject('bucket', 'inputFile');
they both returned the same thing - only date, hash, time and size.
Is there a way to get the content-type of an object?
Thanks!

A couple bugs

Looks like they are a couple potential bugs in version 0.5.0-dev:

1/ In getResponse() line 1776: there is a missing S3:: in front of the second set of $proxy['user'] and $proxy['pass']

if (isset(S3::$proxy['user'], S3::$proxy['pass']) && $proxy['user'] != null && $proxy['pass'] != null)

2/ $rest->headers is used in static functions, but $headers is private in S3Request

3/ Line 731, $uri is undefined in:

self::__triggerError(sprintf("S3::setBucketLogging({$bucket}, {$uri}): [%s] %s",

Great class otherwise - thanks!

Static methods?

Hello, quick question. Is there a reason why this has mostly static methods and variables?

Byte Range Get Response

Is there a way where when we use getObject, we only receive the first X number of bytes of the object? Because I need to parse mp3 id3/metadata, however, it's inefficient to download the ENTIRE s3 object, save it, parse it, then delete it. I simply need the first ~1024 bytes of the file. How would I pass the get header: range= 0-1024

Small typo / paste error while retrieving the owner name within listBuckets()

Within listBuckets() line 355 of 5.0 should read:
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
instead of:
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID

With more context and a -/+ indicating a fix:

    if (!isset($rest->body->Buckets)) return $results; 
    if ($detailed)
    {
        if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
        $results['owner'] = array(
-           'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID
+           'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
        );
        $results['buckets'] = array();
        foreach ($rest->body->Buckets->Bucket as $b)
            $results['buckets'][] = array(
                'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)

inputFile() problem

inputFile() method uses php is_readable() funcion. Results from this function are cached. See http://www.php.net/manual/en/function.is-readable.php

So I had to include a call to clearstatcache() php function before is_readable() call.
http://www.php.net/manual/pt_BR/function.clearstatcache.php.

My problem was because a batch file execution which try to read file names from database and copy from one directory to a S3 bucket. When file is not found in directory, the execution waits some seconds and try to read it again.

Delete non-existing file on S3 return 1

I tried to remove non-existing file on S3 by doing the following:

$result = S3::deleteObject(S3_'BUCKET, $document_uri);

$result value is 1. I expect it to be FALSE or 0 since the file does not exist.

SSL_write() error

Hi there,

Thanks for this great library. I've got it working locally, but when I attempt to upload a file in production I get the following error message:

S3::putObject(): [55] SSL_write() returned SYSCALL, errno = 104
Filename: helpers/s3_helper.php
Line Number: 313

SSL should be set to 'false' by default in the constructor, so I'm not even sure why SSL is an issue. The URL of my app is http://stanfordrosenthal.com/open311/ and it's hosted on Hostgator using CodeIgniter framework.

Thanks!
Stan

Remote Files?

Does this Class work with remote files? For example, I have a Facebook App that browses User galleries, and when they click "Upload" it takes the URL of that photo and sends to my S3 bucket.

Warning: S3::inputFile(): Unable to open input file: http://a1.sphotos.ak.fbcdn.net/photos-ak-ash1.....

S3 class becoming a Trait.

Hi there!
S3 class is just amazing but I'm really interested in setting it into "dryer" and more straightforward approach by transforming it in a Trait.
Anyone did that already?
I'm trying for now and I got some pitfalls such as "non constructor" and "non constant attributes" nature of Traits.
At first shoot I could get some basic stuff such as listing buckets, but for now I'm not able to create neither upload to it.
By looking the following error message we can figure it out some clues:

S3::putBucket(locals-bucket, public-read, ): [AccessDenied] Anonymous access is forbidden for this operation in...

It seems that there's no defined valid S3 credentials!
Once there's no construct function in Traits, I just setted both key and secret in a regular function, but it does not seem to work ;(

Well...that's it, any ideas will be highly appreciated. Cheers!

Bucket folder support?

I can't see that this library supports bucket folders, is that true? Could I persuade someone to issue a pull request adding this functionality?

Great work on this library. I know AWS has their on sdk, but this is small and simple. thanks.

Fatal error:

Hello everyone, i'm getting error like this. i dont know how to fix it, help me

Fatal error: Call to undefined function curl_init() in C:\wamp\www\aws\S3.php on line 772

MAKE FILE PUBLIC

Hi

I am trying to make all file in a bucket public so i can make the stream i am not able to do this with the following code.

putBucket($bucket, S3::ACL_PUBLIC_READ); if (($contents = $s3->getBucket($bucket)) !== false) { foreach ($contents as $object) { $fname = $object['name']; if (($acp = S3::getAccessControlPolicy($bucket,$fname)) !== false) { echo "
";
                print_r($acp);
                echo "
"; // Here you would modify the $acp array... // For example, grant access to the S3 LogDelivery system: $acp["acl"][] = array( "type" => "Group", "uri" => "http://acs.amazonaws.com/groups/s3/LogDelivery", "permission" => "FULL_CONTROL" ); // Then update the policy using the modified $acp array: if (S3::setAccessControlPolicy($bucket, $fname, $acp)) { echo $fname . "Policy updated"; } } } } ``` ?>

Can you help with this???

Error 403 on putObject method

I'm sending my file a base64 encoded file that I decode and send to S3 using the putObject command. The error that Amazon is returning is a 403: "The request signature we calculated does not match the signature you provided. Check your key and signing method."

This has worked for me before and I'm not sure what's broken now. Any ideas?

Here's my code:

define('awsAccessKey', '<REDACTED>');
define('awsSecretKey', '<REDACTED>);

if (!class_exists('S3')) require_once 'S3.php';

//the parameters passed in
$base64 = $_POST['fileData'];
$fileData = base64_decode($base64);
$fileName = $_REQUEST['uri'];
$bucketName = $_REQUEST['bucket'];

$s3 = new S3(awsAccessKey, awsSecretKey);

if ($s3->putObject($fileData, $bucketName, $fileName, S3::ACL_PUBLIC_READ)) {
    echo "http://s3.amazonaws.com/". $bucketName . "/" . $fileName;
} else {
    echo "Upload Failed.\n";
    echo $bucketName . "\n";
    echo $fileName . "\n";
}

__getMIMEType on Windows

$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
sets $ext to 'tmp' because $file contains 'c:\windows\Temp\xyz.tmp', expected result should be the real file extension.

Type

I want it so when I upload something it makes the type be a image/png. How do I do this?

S3 endpoint urls

Since several days ago I'm getting the error:

S3::putObject(): [PermanentRedirect] The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

I'm not sure if Amazon made an update on this, but I made a small investigation on how to solve the issue:

Debugging the class I saw it reaches an url like:
s3.amazon..../bucketname/uri

where should be
bucketname.s3.amazon...../uri

Does this make sense to you?

ps: my bucket location is eu-west-1

putObject retrun true when even the operation fail

Unfortunately I cannot reproduce consistently but lately I start seeing that the file is not uploaded on S3 (I cannot see it in the bucket) but the putObject return true as everything went well. I would like to be more specific but this is what I got so far. I would add more info as I gather more evidence. Any idea what the problem can be ?

Float values in meta headers are converted to int

I am storing some float values in the x-amz-meta-* headers but the values returned from getObjectInfo are casting them to int on line 1908:
is_numeric($value) ? (int)$value : $value;

Not sure why this is included.

Support Amazon Glacier

Amazon Glacier is a very cheap cloud hosting for backups, but there is no PHP client library yet. Could anyone make one baśed on this project?

Won't read all buckets

I have a client account and I can view the files with S3Fox for firefox, but no files are shown with the 0.50 version of S3.php - the same code to view the bucket contents works with several other S3 accounts, just not this one client.

RequestTimeout issue on putObject()

I am using s3-php-class for our document storage service .. And whenever I'd try to upload file bigger than 1 MB in size . I am getting " Warning: S3::putObject(): [RequestTimeout] Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed. in LOCATION/MYFILENAME.php " .

And my file uploading operation gets Fail !!

How to resolve this issue ?

Remote Upload Gives Error

i was trying to upload remote images to my s3 bucket using the amazon s3 php class library, here is my code:

require_once('s3.php');
S3::setAuth("SECRET", "SECRET_CODE");
$filename = md5(time());
$file = "http://i.imgur.com/o0a4i6Z.jpg";
S3::putObject($file, "BUCKET_NAME", $filename, S3::ACL_PUBLIC_READ, array(), array('Content-Type' => 'image/jpeg'));
print "BUCKET_NAME/" . $filename . ".jpg";
this is not going to upload anything in my bucket!
i have also tried

$file = file_get_contents("http://i.imgur.com/o0a4i6Z.jpg");
with no luck
what i am missing? Thanks

Can't seem to turn on SSE

I have the following code:
$metaheaders=array("x-amz-server-side-encryption" => "AES256");
$s3->putObject($file_temp_name, "asdf", $file_name, S3::ACL_PRIVATE, $metaheaders);

The file uploads, but SSE is off. Any help would be greatly appreciated.

Thank you for your time!

SignatureDoesNotMatch Errors

We are using S3 class version 0.4.0 and keep receiving the error below. We use a number of custom meta headers. The most likely culprit is our keyword header that is defined as:

'keyword' => mb_encode_mimeheader($keyword, 'UTF-8');

We seem to receive these errors when $keyword is Russian, Chinese, Japanese, etc.

User Warning: S3::putObject(): [SignatureDoesNotMatch] The request signature we calculated does not match the signature you provided. Check your key and signing method. in S3.php on line 358

[DEPRECATED] Call to undefined function mime_content_type()

Hello,

the mime_content_type() is deprecated and not work script with this error.
In line 3611

// mime_content_type() is deprecated, fileinfo should be configured
$type = isset($exts[$ext]) ? $exts[$ext] : trim(mime_content_type($file));

FIX this please? or a possible alternative?

Thanks

Disappearing Files

For some reason our files are disappearing in the S3, possibly from some sort of expiration. I read a stack overflow page (http://stackoverflow.com/questions/13757671/carrierwave-fog-amazon-s3-images-not-displaying/13757841#13757841) that mentions setting a "fog_public" flag to be true in the "config", but I'm not knowledgeable enough about the internals of the code or Amazon S3 to know if that is correct. Does that sound like something that might need to be added in the PHP S3 class somewhere?

Connect as IAM user

Is it possible to connect to buckets as a limited IAM user as opposed to using aws access key and password?

PermanentRedirect

Hello!
I have amazon s3 bucket & CloudFront for this bucket.
This error while uploading file to a bucket:
S3::putObject: [PermanentRedirect] The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

How to fix it?

Thanks.

PHP error from putObject() method

I'm receiving the following PHP error from the putObject() method.

Severity: Warning
Message: Cannot use a scalar value as an array
Filename: libraries/S3.php
Line Number: 510

This is due to the code only checking if the $input variable is a string, meaning if I want to write just a number to a file it fails to work properly.

To fix I just need to change line 474 to:
if (!is_array($input)) $input = array(

createDistribution

createDistribution does not return distributionId, domain, status values.

Also createDistribution does not have the Logging feature included

Class does not seem to support other regions

Hi,

I have been playing with the S3.php class for a bit now.

I came across a need to have a S3 Bucket in Singapore.

I was unable to find a place to specify the bucket location using the class, so I created it manually. After that, I used that bucket name in my application, but could not upload to it, despite setting permissions to allow everyone to do everything on that bucket.

I suspect that it is due to the multiple locations of hard-coded s3.amazonaws.com in the code, and also, the fact that the class does not seem to follow any 302 HTTP redirect errors.

Hurgh

getObjectStorageClass Method

I'm not too familiar with github but thought I'd share a method I wrote to get the storage class of an item. I pulled most of the info from here: https://forums.aws.amazon.com/message.jspa?messageID=312224
There might be better ways to do it but the code works so thought I'd share:

/**
* Get object StorageClass
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @return string | false
*/
public static function getObjectStorageClass($bucket, $uri)
{
$rest = new S3Request('GET', $bucket, '', self::$endpoint);
$rest->setParameter('prefix', $uri);
$rest = $rest->getResponse();
if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::triggerError(sprintf("S3::getObjectStorageClass({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE
, LINE);
return false;
}
return (string) $rest->body->Contents->StorageClass;
}

URL Endpoint

Is it possible to get the bucket and file endpoint url thru the api?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.