Giter Site home page Giter Site logo

php-sdk's Introduction

Transloadit PHP SDK

Test Actions Status Code coverage Packagist PHP Version Support License

A PHP Integration for Transloadit's file uploading and encoding service

Intro

Transloadit is a service that helps you handle file uploads, resize, crop and watermark your images, make GIFs, transcode your videos, extract thumbnails, generate audio waveforms, and so much more. In short, Transloadit is the Swiss Army Knife for your files.

This is a PHP SDK to make it easy to talk to the Transloadit REST API.

Install

composer require transloadit/php-sdk

Keep your Transloadit account's Auth Key & Secret nearby. You can check the API credentials page for these values.

Usage

1. Upload and resize an image from your server

This example demonstrates how you can use the SDK to create an Assembly on your server.

It takes a sample image file, uploads it to Transloadit, and starts a resizing job on it.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit([
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
]);

$response = $transloadit->createAssembly([
  'files' => ['/PATH/TO/FILE.jpg'],
  'params' => [
    'steps' => [
      'resize' => [
        'robot' => '/image/resize',
        'width' => 200,
        'height' => 100,
      ],
    ],
  ],
]);

// Show the results of the assembly we spawned
echo '<pre>';
print_r($response);
echo '</pre>';

2. Create a simple end-user upload form

This example shows you how to create a simple Transloadit upload form that redirects back to your site after the upload is done.

Once the script receives the redirect request, the current status for this Assembly is shown using Transloadit::response().

Note: There is no guarantee that the Assembly has already finished executing by the time the $response is fetched. You should use the notify_url parameter for this.
<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit([
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
]);

// Check if this request is a Transloadit redirect_url notification.
// If so fetch the response and output the current assembly status:
$response = Transloadit::response();
if ($response) {
  echo '<h1>Assembly Status:</h1>';
  echo '<pre>';
  print_r($response);
  echo '</pre>';
  exit;
}

// This should work on most environments, but you might have to modify
// this for your particular setup.
$redirectUrl = sprintf('http://%s%s', $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']);

// Setup a simple file upload form that resizes an image to 200x100px
echo $transloadit->createAssemblyForm([
  'params' => [
    'steps' => [
      'resize' => [
        'robot' => '/image/resize',
        'width' => 200,
        'height' => 100,
      ],
    ],
    'redirect_url' => $redirectUrl,
  ],
]);
?>
<h1>Pick an image to resize</h1>
<input name="example_upload" type="file">
<input type="submit" value="Upload">
</form>

3. Integrate the jQuery plugin into the previous example

Integrating the jQuery plugin simply means adding a few lines of JavaScript to the previous example. Check the HTML comments below to see what changed.

Alternatively, check out Uppy, our next-gen file uploader for the web.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit([
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
]);

$response = Transloadit::response();
if ($response) {
  echo '<h1>Assembly Status:</h1>';
  echo '<pre>';
  print_r($response);
  echo '</pre>';
  exit;
}

$redirectUrl = sprintf('http://%s%s', $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']);

echo $transloadit->createAssemblyForm([
  'params' => [
    'steps' => [
      'resize' => [
        'robot' => '/image/resize',
        'width' => 200,
        'height' => 100,
      ],
    ],
    'redirect_url' => $redirectUrl,
  ],
]);
?>
<!--
  Including the jQuery plugin is as simple as adding jQuery and including the
  JS snippet for the plugin. See https://transloadit.com/docs/sdks/jquery-sdk/
-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
  var tlProtocol = (('https:' === document.location.protocol) ? 'https://' : 'http://');
  document.write(unescape("%3Cscript src='" + tlProtocol + "assets.transloadit.com/js/jquery.transloadit2.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
  $(document).ready(function() {
    // Tell the transloadit plugin to bind itself to our form
    $('form').transloadit();
  });
</script>
<!-- Nothing changed below here -->
<h1>Pick an image to resize</h1>
<form>
  <input name="example_upload" type="file">
  <input type="submit" value="Upload">
</form>

4. Fetch the Assembly Status JSON

You can use the getAssembly method to get the Assembly Status.

<?php
require 'vendor/autoload.php';
$assemblyId = 'YOUR_ASSEMBLY_ID';

$transloadit = new Transloadit([
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
]);

$response = $transloadit->getAssembly($assemblyId);

echo '<pre>';
print_r($response);
echo '</pre>';

5. Create an Assembly with a Template.

This example demonstrates how you can use the SDK to create an Assembly with Templates.

You are expected to create a Template on your Transloadit account dashboard and add the Template ID here.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit([
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
]);

$response = $transloadit->createAssembly([
  'files' => ['/PATH/TO/FILE.jpg'],
  'params' => [
    'template_id' => 'YOUR_TEMPLATE_ID',
  ],
]);

// Show the results of the assembly we spawned
echo '<pre>';
print_r($response);
echo '</pre>';

Signature Auth

Signature Authentication is done by the PHP SDK by default internally so you do not need to worry about this :)

Example

For fully working examples take a look at examples/.

API

$Transloadit = new Transloadit($properties = []);

Creates a new Transloadit instance and applies the given $properties.

$Transloadit->key = null;

The auth key of your Transloadit account.

$Transloadit->secret = null;

The auth secret of your Transloadit account.

$Transloadit->request($options = [], $execute = true);

Creates a new TransloaditRequest using the $Transloadit->key and $Transloadit->secret properties.

If $execute is set to true, $TransloaditRequest->execute() will be called and used as the return value.

Otherwise the new TransloaditRequest instance is being returned.

$Transloadit->createAssemblyForm($options = []);

Creates a new Transloadit assembly form including the hidden 'params' and 'signature' fields. A closing form tag is not included.

$options is an array of TransloaditRequest properties to be used. For example: "params", "expires", "endpoint", etc..

In addition to that, you can also pass an "attributes" key, which allows you to set custom form attributes. For example:

$Transloadit->createAssemblyForm(array(
  'attributes' => array(
    'id'    => 'my_great_upload_form',
    'class' => 'transloadit_form',
  ),
));

$Transloadit->createAssembly($options);

Sends a new assembly request to Transloadit. This is the preferred way of uploading files from your server.

$options is an array of TransloaditRequest properties to be used with the exception that you can also use the waitForCompletion option here:

waitForCompletion is a boolean (default is false) to indicate whether you want to wait for the Assembly to finish with all encoding results present before the callback is called. If waitForCompletion is true, this SDK will poll for status updates and return when all encoding work is done.

Check example #1 above for more information.

$Transloadit->getAssembly($assemblyId);

Retrieves the Assembly status json for a given Assembly ID.

$Transloadit->cancelAssembly($assemblyId);

Cancels an assembly that is currently executing and prevents any further encodings costing money.

This will result in ASSEMBLY_NOT_FOUND errors if invoked on assemblies that are not currently executing (anymore).

Transloadit::response()

This static method is used to parse the notifications Transloadit sends to your server.

There are two kinds of notifications this method handles:

  • When using the redirect_url parameter, and Transloadit redirects back to your site, a $_GET['assembly_url'] query parameter gets added. This method detects the presence of this parameter and fetches the current assembly status from that url and returns it as a TransloaditResponse.
  • When using the notify_url parameter, Transloadit sends a $_POST['transloadit'] parameter. This method detects this, and parses the notification JSON into a TransloaditResponse object for you.

If the current request does not seem to be invoked by Transloadit, this method returns false.

$TransloaditRequest = new TransloaditRequest($properties = []);

Creates a new TransloaditRequest instance and applies the given $properties.

$TransloaditRequest->key = null;

The auth key of your Transloadit account.

$TransloaditRequest->secret = null;

The auth secret of your Transloadit account.

$TransloaditRequest->method = 'GET';

Inherited from CurlRequest. Can be used to set the type of request to be made.

$TransloaditRequest->curlOptions = [];

Inherited from CurlRequest. Can be used to tweak cURL behavior using any cURL option that your PHP/cURL version supports.

Here is an example that illustrates using this option to change the timeout of a request (drastically, to 1ms, just to prove you can make the SDK abort after a time of your choosing).

The default timeouts and options depend on the cURL version on your system and can be verified by checking phpinfo() and the curl_setopt documentation.

$TransloaditRequest->endpoint = 'https://api2.transloadit.com';

The endpoint to send this request to.

$TransloaditRequest->path = null;

The url path to request.

$TransloaditRequest->url = null;

Inherited from CurlRequest. Lets you overwrite the above endpoint / path properties with a fully custom url alltogether.

$TransloaditRequest->fields = [];

A list of additional fields to send along with your request. Transloadit will include those in all assembly related notifications.

$TransloaditRequest->files = [];

An array of paths to local files you would like to upload. For example:

$TransloaditRequest->files = array('/my/file.jpg');

or

$TransloaditRequest->files = array('my_upload' => '/my/file.jpg');

The first example would automatically give your file a field name of 'file_1' when executing the request.

$TransloaditRequest->params = [];

An array representing the JSON params to be send to Transloadit. You do not have to include an 'auth' key here, as this class handles that for you as part of $TransloaditRequest->prepare().

$TransloaditRequest->expires = '+2 hours';

If you have configured a '$TransloaditRequest->secret', this class will automatically sign your request. The expires property lets you configure the duration for which the signature is valid.

$TransloaditRequest->headers = [];

Lets you send additional headers along with your request. You should not have to change this property.

$TransloaditRequest->execute()

Sends this request to Transloadit and returns a TransloaditResponse instance.

$TransloaditResponse = new TransloaditResponse($properties = []);

Creates a new TransloaditResponse instance and applies the given $properties.

$TransloaditResponse->data = null;

Inherited from CurlResponse. Contains an array of the parsed JSON response from Transloadit.

You should generally only access this property after having checked for errors using $TransloaditResponse->error().

$TransloaditResponse->error();

Returns false or a string containing an explanation of what went wrong.

All of the following will cause an error string to be returned:

  • Network issues of any kind
  • The Transloadit response JSON contains an {"error": "..."} key
  • A malformed response was received

Note: You will need to set waitForCompletion = True in the $Transloadit->createAssembly($options) function call.

Contributing

Feel free to fork this project. We will happily merge bug fixes or other small improvements. For bigger changes you should probably get in touch with us before you start to avoid not seeing them merged.

Versioning

This project implements the Semantic Versioning guidelines.

Releases will be numbered with the following format:

<major>.<minor>.<patch>

And constructed with the following guidelines:

  • Breaking backward compatibility bumps the major (and resets the minor and patch)
  • New additions without breaking backward compatibility bumps the minor (and resets the patch)
  • Bug fixes and misc changes bumps the patch

For more information on SemVer, please visit http://semver.org/.

Releasing a new version

# 1. update CHANGELOG.md
# 2. update composer.json
# 3. commit all your work
source env.sh && VERSION=3.1.0 ./release.sh

License

MIT Licensed

php-sdk's People

Contributors

aberkhout avatar acconut avatar alexsoft avatar bmilleare avatar dependabot[bot] avatar eerison avatar ethanwillis avatar felixge avatar goto-bus-stop avatar ifedapoolarewaju avatar kvz avatar michaelkasper avatar missing-tech avatar nervetattoo avatar nqst avatar tim-kos 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-sdk's Issues

Relative path breaks implementation on missing version

In the commit (b0cde0c) the SDK checks the composer.json file for a version number.

But the path to the composer file in CurlRequest.php is relative. So in our implementation it references to the composer.json file in our own project.

This results in a 'Undefined property: stdClass::$version' exception.

Signatures NEVER match.

Maybe I'm doing something wrong, which would be a direct result of how unclear the Docs are on Signature Generation, but when I generate a signature using this API or with the code suggested in the Docs the signature strings never match the ones that are expected.

I tried the fixtures on the 'API Credentials' page to check this SDK's signature generation and even then the signatures didn't match.

As listed on: https://transloadit.com/docs/api-docs#authentication (2.4 Example)

{ auth: { expires: "2010/10/19 09:01:20+00:00", key: "2b0c45611f6440dfb64611e872ec3211"}, steps: { encode: { robot: "/video/encode" } } }

Auth secret used:

d805593620e689465d7da6b8caf2ac7384fdb7e9

The expected Signature:

fec703ccbe36b942c90d17f64b71268ed4f5f512

The signature this SDK generates:

d748d622eea9a1fb5128466bdd5a66ce6b7a8b04

Are there specific PHP-settings that are not listed here? Is there something we still need to do?

Lib does not return exception

When there is some problem the lib didn't return a exception

e.g

curl: 6: Could not resolve host: api2.transloadit.com

Deprecation warning

When making a request with the sdk I get this deprecation warning.

Warning: strtotime(): It is not safe to rely on the system's timezone settings.
You are *required* to use the date.timezone setting or the date_default_timezone_set() function.
In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier.
We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.
in .../php-sdk/lib/transloadit/TransloaditRequest.php on line 33

Suggestion: CURL depricated functions (PHP 5.5)

This is what a customer wrote to us:


On CurlRequest.php of the Transloadit PHP API, the following warning is generated:

curl_setopt_array(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead

I have checked and notice that this CURLFile class appears only in PHP 5.5 and so you will need to check the PHP version and write two versions.

Its not worth my time to fix, but it triggers my debugger ever time that I use it.

Doesn't work for PHP 5.6.15?

Hey guys, I've tried the API for uploading and processing videos, and have encountered that it works just fine with PHP 5.5.9, but not with PHP 5.6.15. The payload variables are also totally different in both the cases despite same PHP script being used in both environments.

PHP 5.5.9: (correct)
http://api2.transloadit.com/assemblies/4f4d38c016a311e6a9c1d1ab1c9ca004

PHP 5.6.15: (incorect)
http://api2.transloadit.com/assemblies/dfbee9d016a311e6b7d7e5e0f9f5a61f

Could you help me out here please?

proposal for new major

Hi I'm here again :)

I would like to know if make sense to create a new release change all structure

  • use PSR4
  • create Models and Services
  • use symfony/http-client for requests
  • use symfony/serializer to converte object to json
  • use github actions (it`s optional, but should be good use only GitHub features)
  • use twig/twig template engine to form (It's not really clear why do we need this)
  • create a new doc
  • create tests
  • add coverage
  • add phpcs
  • create pipeline to generate release

Questions

  • I saw some examples using Jquery, make sense we keep this in php-sdk?
  • Why do we need this assemblyForm
    public function createAssemblyForm($options = array()) {
  • Can we support just php version ^7.2 (>=7.2)?

Fixes: #30 #31 #32

add uploaded files to assembly

On the SDK documentation and on sample assembly request the files are added as path value

'files' => array('/PATH/TO/FILE.jpg')

I am adding the file from an upload that is not moved to any folder, so at this point I have the temp file and temp file name.

Is there any way to set the filename without move the temporary file a directory to keep original file name, because I use the uploaded file once the assembly is done the original file name is lost as it is reading the temporary file.

Remove files not used

I can see many files that should not be in the repository or it's unnecessary

I'll list them

  • .vscode
  • tool
  • .empty
  • #52
  • release.sh ?
  • Makefile ?

can we remove them?

Implement "waitForCompletion" parameter for the createAssembly function

From the node-sdk:

waitForCompletion - A boolean (default is false) to indicate whether you want to wait for the Assembly to finish with all encoding results present before the callback is called. If waitForCompletion is true, this SDK will poll for status updates and call doneCb when all encoding work is done. During each polling action, progressCb(ret) is called with the current Assembly Status in assemblyProgress inside a result object as its only argument.

This needs to be implemented here.

Make timeouts configurable

And set defaults, then, we can also communicate those in docs.

Currently it is not clear what the timeout values are because we use curl_exec, meaning these options: https://www.php.net/manual/en/function.curl-setopt.php, but as you can see, default values aren't listed there often. I'm sure we could get them somehow (and maybe they even depend on your php/curl binding version), but all of this is a hassle we shouldn't let our customers go through.

Request async

I'm needing to do request async what do you think to add guzzle on dependencies?

Is it still maintained?

Just to make sure, is this repository maintained or is abandoned? I feel that there isn't anyone to review the PR or care about improve the code and we continue still using a code made 5 years 9 years ago or more.

If using 'tmp_file' you will need to use move_uploaded_file() first

As stated in the title you will need to use move_uploaded_file() if you are handling uploads yourself and using tmp_file. This is because 'tmp_file' will remove the file extension which breaks parsing on the Transloadit side.

See the following resources:

  1. https://www.php.net/manual/en/function.move-uploaded-file.php#refsect1-function.move-uploaded-file-examples
  2. https://stackoverflow.com/questions/4693144/uploaded-picture-in-tmp-is-without-file-extension

We will need to update the documentation with a note about this just in case other people want to try and exert more control without using Transloadit::createAssemblyForm()

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.