A standalone Amazon S3 (REST) client for PHP 5/CURL

Last update: May 3, 2022

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)

GitHub

https://github.com/tpyo/amazon-s3-php-class
Comments
  • 1. Added AWS v4 signature supports.

    Just Added AWS v4 signature supports.

    Using 'AWS4-HMAC-SHA256' for authorization.

    For backward compatible , you must calling $s3->setSignatureVersion('v4') or S3::setSignatureVersion('v4') before requests.

    Only tested at China Beijing region, i think Franckfurt should be okay too.

    ref: #120, #96

    Reviewed by racklin at 2016-12-14 12:52
  • 2. The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

    The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

    This error happens when attempting to upload to a bucket other than us-standard.

    Reviewed by nodesocket at 2013-05-12 04:53
  • 3. 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

    Reviewed by hurgh at 2012-02-07 04:46
  • 4. Using php to upload multiple media files

    $bucket = 'cdn.blkbxcg.com/urlifemedia/'; $orderid = Session::get('orderid'); $target_path = $orderid . '/' . $type . '/' . $_FILES['file']['name'][$i]; S3::putObject( $_FILES['file']['name'][$i], $bucket . 'testing', $target_path, S3::ACL_PUBLIC_READ_WRITE );

    type is either 'images' or 'video', whenever my script runs it creates the folders and files just fine. Whenever I download the media from transmit file and open it, it says the file is corrupted. When I delete the newly created folder, transmit (ftp program) deletes the folder but it gives me a warning also saying 'couldn't find folder'.

    Reviewed by l337 at 2015-03-26 19:43
  • 5. 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!

    Reviewed by yocheved at 2014-01-27 10:54
  • 6. 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.

    Reviewed by NazarkinRoman at 2012-04-23 09:40
  • 7. 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

    Reviewed by smartinec at 2011-09-29 15:36
  • 8. "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256."

    AWS::S3::Errors::InvalidRequest The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

    I have same problem, with Frankfurt server, as in this question. http://stackoverflow.com/questions/26533245/the-authorization-mechanism-you-have-provided-is-not-supported-please-use-aws4

    Can you add new type of authorization?

    Reviewed by Kulikovpavel at 2015-11-29 12:00
  • 9. Support Multipart Upload

    From Amazon's REST API, supporting multipart uploads SHOULD work. I created a method called postObject() whose sole purpose is to initiate an upload (http://goo.gl/8QoNFI) and get the returned upload ID, which could be used in putObject() when uploading parts (http://goo.gl/f1d0QB). To keep it simple, I'm not doing anything but the bare requirements (no encryption, no meta data, etc)

        public static function postObject($input, $bucket, $uri)
        {
            $rest = new S3Request('POST', $bucket, $uri);
            $rest->setParameter('uploads', '');
            $rest->getResponse();
            return $rest->response;
        }
    

    Response:

    [code] => SignatureDoesNotMatch
    [message] => The request signature we calculated does not match the signature you provided. Check your key and signing method.
    

    cURL info:

    POST /93F2K4M?uploads HTTP/1.1
    User-Agent: S3/php
    Accept: */*
    Host: kd-dev-dave.s3.amazonaws.com
    Date: Mon, 19 May 2014 22:21:24 GMT
    Authorization: AWS AKIAJATBHXMIPX6PLAOA:uUEvM5XBYZtqLWp1Po1b/TInOA4=
    

    Thoughts on what is going wrong?

    Additional info:

    • Using the same file, I am able to use putObject(), so the key/secret and file are totally fine
    • I've tried using a straight copy of putObject (since it's similar) with the same error, so I'm assuming it's something to do with the POST verb?
    Reviewed by daverogers at 2014-05-19 22:37
  • 10. 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"

    Reviewed by sumachaa at 2011-08-24 02:13
  • 11. Fixes stat cache issue from #89

    filesize() may receive cached data, meaning the file size sent to AmazonS3 may be incorrect, so it's important to clear the cache before requesting the filesize.

    Reviewed by clphillips at 2014-12-30 19:12
  • 12. openssl_free_key() is deprecated in PHP8

    From the php80 release notes:

    . The openssl_x509_free() function is deprecated and no longer has an effect, instead the OpenSSLCertificate instance is automatically destroyed if it is no longer referenced. . The openssl_pkey_free() (and its alias openssl_free_key) function is deprecated and no longer has an effect, instead the OpenSSLAsymmetricKey instance is automatically destroyed if it is no longer referenced.

    And there is a case of openssl_free_key() @ S3.php

    Maybe it should be replaced to something like:

    if (PHP_MAJOR_VERSION < 8) {
        openssl_free_key(self::$__signingKeyResource);
    }
    self::$__signingKeyResource = null;
    

    Ciao :-)

    Reviewed by stronk7 at 2022-01-10 13:47
  • 13. filter out empty headers

    Fixes issues #157 & #171.

    It turns out that ListBuckets does not work on non-amazon services due to a 403 SignatureDoesNotMatch error caused by some empty headers.

    This minor change fixes that.

    Reviewed by dcmexy at 2021-05-16 00:51
  • 14. ListBuckets does not work on non-amazon services

    Here is an code example that I have here while trying to connect to Linode's S3 cloud storage service:

    	require 'includes/S3.php';
    	ini_set("display_errors", "on");
    	error_reporting(E_ALL);
    	
    	$AccessKey = "[REMOVED]"; //private info
    	$SecretKey = "[REMOVED]"; //private info
    	$EndPoint  = "us-east-1.linodeobjects.com";
    	$Region = "us-east-1";
    	
    	$s3Client = new S3($AccessKey, $SecretKey);					
    	if (isset($EndPoint)) $s3Client->setEndPoint($EndPoint);
    	if (isset($Region)) $s3Client->setRegion($Region);
    	$s3Client->setSSL(true);
    	
    	$buckets = $s3Client->listBuckets();
    

    As a result, I get this error: Warning: S3::listBuckets(): [403] Unexpected HTTP status in includes/S3.php on line 440

    If I go into the file and print out the $rest object to get more information, I get:

    stdClass Object
    (
        [error] => 
        [body] => SimpleXMLElement Object
            (
                [Code] => SignatureDoesNotMatch
                [RequestId] => tx00000000000000471bbb4-005f306dbc-158bf75-default
                [HostId] => 158bf75-default-default
            )
    
        [headers] => Array
            (
                [date] => 1597009340
                [type] => application/xml
                [size] => 200
            )
    
        [code] => 403
    )
    

    On the other hand, if I change the above code to an amazon service:

    	$AccessKey = "[REMOVED]";
    	$SecretKey = "[REMOVED]";
    	$EndPoint = "s3.amazonaws.com";
    	$Region = "us-east-1";
    

    Authentication works properly on Amazon's services.

    Just to make sure this isn't a problem on Linode's end, I tried doing this on another third party (MojoCloud) and ran into the same issue.

    Finally, just to make sure that the information is correct, I tried using aws-sdk-php beneath the tpyo library to see if I can connect to S3 using the same info:

    	$credentials = new Aws\Credentials\Credentials($AccessKey, $SecretKey);
    
    	$s3Client = new Aws\S3\S3Client([
    		'region' => $Region,
    		'version' => 'latest',
    		'endpoint' => "https://" . $EndPoint,
    		'credentials' => $credentials
    		]);
    		
    	$result = $s3Client->listBuckets();
    	
    	echo "<PRE>";
    	print_r($result["Buckets"]);
    	exit;
    

    And sure enough, this works for all three services (Amazon, MojoCloud, Linode). This way, I know the connection information is correct.

    What I suspect here is a generalization problem with __getSignatureV4() where a valid signature is generated on amazon services, but not on non-amazon services.

    Please let me know if any more information is needed here. If any of the maintainers here needs an access key / secret key to try troubleshooting this and debugging this on Linode's object service, please let me know.

    Or if there's something obvious I'm missing, please let me know :)

    Reviewed by SeventhCycle at 2020-08-09 22:02
  • 15. Could I prevent invalidation?

    Hi there, I got for 1 one day Amazon CloudFront usage costs are up to $. (56,488%) compared to the whole previous month for my tiny project! Because of the invalidation, am I able to prevent files invalidating, and upload files directly?

    Reviewed by aolamer at 2020-08-03 17:50
Configure Magento 2 to send email using Google App, Gmail, Amazon Simple Email Service (SES), Microsoft Office365 and many other SMTP (Simple Mail Transfer Protocol) servers
Configure Magento 2 to send email using Google App, Gmail, Amazon Simple Email Service (SES), Microsoft Office365 and many other SMTP (Simple Mail Transfer Protocol) servers

Magento 2 SMTP Extension - Gmail, G Suite, Amazon SES, Office 365, Mailgun, SendGrid, Mandrill and other SMTP servers. For Magento 2.0.x, 2.1.x, 2.2.x

Apr 7, 2022
Composer Curl Plugin

Composer Curl Plugin Install Install plugin $ composer global require ngyuki/composer-curl-plugin:dev-master Example Install symfony $ composer req

May 6, 2019
Echo your public IP address with a very simple cURL request

Echo your public IP address with a very simple cURL request

Apr 10, 2022
A simple, standalone, modern PHP class inspector and mapper library, wrapping PHPs native reflection in a fluent interface

A simple, standalone, modern PHP class inspector and mapper library, wrapping PHPs native reflection in a fluent interface.

May 6, 2022
Pat eu cookies law - 🌝 EU Cookie Law Compliance: A Textpattern plugin (or standalone script) for Third-Party Cookies (RGPD compliance)
Pat eu cookies law - 🌝 EU Cookie Law Compliance: A Textpattern plugin (or standalone script) for Third-Party Cookies (RGPD compliance)

pat_eu_cookies_law EU Cookie Law Compliance: A Textpattern plugin (or a standalone script) for Third-Party Cookies. A simple solution that respects th

Aug 16, 2020
A PHP 7.4+ library to consume the Confluent Schema Registry REST API

A PHP 7.4+ library to consume the Confluent Schema Registry REST API. It provides low level functions to create PSR-7 compliant requests that can be used as well as high level abstractions to ease developer experience.

May 3, 2022
A PHP library to support implementing representations for HATEOAS REST web services.

Hateoas A PHP library to support implementing representations for HATEOAS REST web services. Installation Working With Symfony Usage Introduction Conf

May 12, 2022
The fastest way to make a powerful JSON:API compatible Rest API with Laravel.
The fastest way to make a powerful JSON:API compatible Rest API with Laravel.

The first fully customizable Laravel JSON:API builder. "CRUD" and protect your resources with 0 (zero) extra line of code. Installation You can instal

May 17, 2022
A Magento 2 module that enables configurable CORS Headers on the GraphQL and REST APIs

Magento 2 CORS Magento Version Support Ever try to work with the Magento GraphQL API or REST API from your browser and see the following? Access to XM

Apr 4, 2022
API REST para CRUD de usuários

Crud de Usuários QUAL A FUNÇÃO DA API? Esta API tem como objetivo cadastrar usuários e seus respectivos endereços por meio de requests e também fazer

Mar 26, 2022
Complete Pipedrive API client for PHP

Complete Pipedrive API client for PHP Contribute by referral code / link This won't take much time. You could use my referral code or link to get up t

May 6, 2022
A GETTR.com client library written in PHP with Laravel support.
A GETTR.com client library written in PHP with Laravel support.

Gettr API Clinet PHP A GETTR.com client library written in PHP with Laravel support. This library uses unofficial publicly accessible API endpoints of

Jan 18, 2022
SendCloud client for PHP

SendCloud client for PHP Installation composer require guangda/sendcloud Example $mailData = [ 'to'=>'[email protected]', 'subject'=>'test',

Aug 27, 2021
Bearer client for the PHP programming language

Bearer PHP Client This is the official PHP client for interacting with Bearer.sh. Installation Install the package by running: composer require bearer

Jan 8, 2021
The most widely used PHP client for RabbitMQ

php-amqplib This library is a pure PHP implementation of the AMQP 0-9-1 protocol. It's been tested against RabbitMQ. The library was used for the PHP

May 26, 2022
kafka php client
kafka php client

Kafka-php 中文文档 Kafka-php is a pure PHP kafka client that currently supports greater than 0.8.x version of Kafka, this project v0.2.x and v0.1.x are in

May 20, 2022
Artax is an asynchronous HTTP client for PHP based on Amp

Artax is an asynchronous HTTP client for PHP based on Amp. Its API simplifies standards-compliant HTTP resource traversal and RESTful web service consumption without obscuring the underlying protocol. The library manually implements HTTP over TCP sockets; as such it has no dependency on ext/curl.

Mar 20, 2021
Grpc go-server php-client

Grpc go-server php-client

Jan 24, 2022
Idiomatic PHP client for Google Compute.

Google Compute for PHP Idiomatic PHP client for Google Compute. API Documentation NOTE: This repository is part of Google Cloud PHP. Any support reque

Dec 10, 2021