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

Overview

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)
Comments
  • Added AWS v4 signature supports.

    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

    opened by racklin 22
  • 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.

    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.

    opened by nodesocket 9
  • Class does not seem to support other regions

    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

    opened by hurgh 7
  • Using php to upload multiple media files

    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'.

    opened by l337 6
  • get content-type for object

    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!

    opened by yocheved 6
  • PermanentRedirect

    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.

    opened by NazarkinRoman 6
  • SignatureDoesNotMatch Errors

    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

    opened by smartinec 6
  • "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?

    opened by Kulikovpavel 4
  • Support Multipart Upload

    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?
    opened by daverogers 4
  • Cloudfront CDN not working

    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"

    opened by sumachaa 4
  • Fixes stat cache issue from #89

    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.

    opened by clphillips 3
  • De-static-ified version of S3 with tagging

    De-static-ified version of S3 with tagging

    Sorry to make this announcement as an "issue" but I've "forked" this class and made some big changes.

    https://github.com/networkjackbb/third-party/tree/main/amazon-s3-php-class

    Please check the readme for more info. All props to Donovan.

    opened by networkjackbb 0
  • openssl_free_key() is deprecated in PHP8

    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 :-)

    opened by stronk7 0
  • filter out empty headers

    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.

    opened by dcmexy 0
  • ListBuckets does not work on non-amazon services

    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 :)

    opened by SeventhCycle 12
Releases(v0.5.1)
Owner
Donovan Schönknecht
Donovan Schönknecht
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

MagePal :: Magento Extensions 303 Oct 7, 2022
WebScraping que busca 15 produtos em destaque na amazon e mercado livre, ordenando pelo menor preço.

WebScraping WebScraping que busca 15 produtos em destaque na amazon e mercado livre, ordenando pelo menor preço. Na criação do site foram usados Html,

Welson 3 Nov 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.

smpl 9 Sep 1, 2022
PHP Standalone Validation Library

Rakit Validation - PHP Standalone Validation Library PHP Standalone library for validating data. Inspired by Illuminate\Validation Laravel. Features A

Rakit Lab 727 Dec 30, 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 a standalone script) for Third-Party Cookies. A simple solution that respects th

Patrick LEFEVRE 3 Aug 16, 2020
The Pantheon CLI — a standalone utility for performing operations on the Pantheon Platform

terminus : Pantheon's Command-Line Interface Status About Terminus is Pantheon's Command Line Interface (CLI), providing at least equivalent functiona

Pantheon 290 Dec 26, 2022
Composer Curl Plugin

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

Toshiyuki Goto 4 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

Lucas Burlingham 13 Apr 10, 2022
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.

Flix.TECH 38 Sep 1, 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

William Durand 998 Dec 5, 2022
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

BinarCode 394 Dec 23, 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

Graycore, LLC 62 Dec 8, 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

Gabriel Cruz 1 Mar 26, 2022
Desafio de Back-End da Alura: Crie uma API Rest funcional focada em controle financeiro.

Lumen PHP Framework Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expressive, elegant syntax. We believe d

Rejman Nascimento 0 Dec 31, 2022
Modello base con tutto il docker configurato per php7.4, mariadb, vue3, apache...con esempi di component e chiamate rest interne

Applicazione base per utilizzare laravel con docker, php7.4, apache, mariadb10, vue3 Semplice installazione corredate di rotte web e api di base, 3 co

null 0 Jul 14, 2022
ILIAS Rest Api

flux-ilias-rest-api ILIAS Rest Api This is not a ILIAS plugin Installation flux-ilias-rest-api In flux-ilias-ilias-base RUN /flux-ilias-ilias-base/bin

null 4 Dec 14, 2022
Twitter Clone API Rest with Laravel 9

TW Main API (Twitter Clone) Setup Installation Before docker-compose up Get copy the .env.example to .env Set Mail variables Set Pusher Variables with

Jesus Eduardo 0 Jul 31, 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

Israel Ortuño 155 Dec 7, 2022
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

null 10 Dec 13, 2022