Last updated: May 29, 2024

<span aria-hidden="true" id="async-php-integration-for-efficient-transloadit-use"></span>

# Async PHP integration for efficient Transloadit use

![Joseph Grabski](/assets/images/teammates/joseph2.png?dpl=dpl_6nhQNS5wkVkPZWuKMzXcWrAHNJL5)

**Joseph Grabski**

Content Lead · Rochester, United Kingdom · Show bio

[](https://x.com/joe%5Fgrabski)[](https://github.com/Missing-Tech)

In an age when data is only a few seconds away, the last thing we want is for our users to waste time waiting. That's why today, using PHP, we're demonstrating how to use[Assembly Notifications](/docs/topics/webhooks.md) to interact with Transloadit in Async Mode, so you can spend less time waiting for transcoding Steps to complete.

![PHP logo](/_next/static/immutable/media/opengraph-image.3u2wp8-f9b90v.png)

To set up Transloadit to work asynchronously, we'll need to combine our open source file uploader[Uppy⁠](https://uppy.io/), one local-notification option ([Cloudflare Tunnel⁠](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/),[ngrok⁠](https://ngrok.com/), or[@transloadit/notify-url-relay⁠](https://www.npmjs.com/package/@transloadit/notify-url-relay)), a[MySQL database⁠](https://www.mysql.com/), and a little PHP to put it all together. We'll be using vanilla PHP, which will hopefully be easy enough to understand and adapt for people using frameworks such as Laravel, CodeIgniter, Symfony, or CakePHP.

<span aria-hidden="true" id="setting-up-the-website"></span>

## Setting up the website

The first thing we must do is create an Assembly. To keep things simple, we'll use the[Robodog Dashboard⁠](https://uppy.io/docs/transloadit/) to upload files to Transloadit.

(Disclaimer: Robodog has now been deprecated and replaced with a[Transloadit plugin⁠](https://uppy.io/docs/transloadit/))

Please create a new folder for the project and then open a new file called `index.php`.

Next, add our basic HTML skeleton:

```html
<html>
  <link
    rel="stylesheet"
    href="https://releases.transloadit.com/uppy/robodog/v1.10.12/robodog.min.css"
  />
  <script src="https://releases.transloadit.com/uppy/robodog/v1.10.12/robodog.min.js"></script>
  <body>
    <div id="dashboard"></div>
    <script>
      Robodog.dashboard('#dashboard', {
        params: {
          auth: {
            key: 'AUTH_KEY',
          },
          template_id: 'TEMPLATE_ID',
          fields: {
            url: window.location.href,
          },
        },
      })
    </script>
  </body>
</html>

```

<span aria-hidden="true" id="setting-up-the-database"></span>

## Setting up the database

Our next step is to create the database. After[installing MySQL⁠](https://dev.mysql.com/doc/mysql-installation-excerpt/8.0/en/general-installation-issues.html), launch the MySQL shell terminal (likely just `mysql` on your system). To get our database up and running, we'll need to execute several commands.

1. Switch to SQL mode

```sql
\sql  
```

2. Connect to the local MySQL server

```sql
\connect root@localhost  
```

3. Create the database

```sql
CREATE DATABASE transloadit;  
USE transloadit;  
```

4. Create a table to store information on our Assemblies and an auto-generated timestamp of when we received a pingback

```sql
CREATE TABLE assemblies (  
  id VARCHAR(100) PRIMARY KEY,  
  ok VARCHAR(30) NOT NULL,  
  http_code INT(3) NOT NULL,  
  timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP  
);  
```

If you run `DESCRIBE assemblies;`, you should see a table like so:

```plaintext
+-----------+--------------+------+-----+-------------------+-------------------+
| Field     | Type         | Null | Key | Default           | Extra             |
+-----------+--------------+------+-----+-------------------+-------------------+
| id        | varchar(100) | NO   | PRI | NULL              |                   |
| ok        | varchar(30)  | NO   |     | NULL              |                   |
| http_code | int          | NO   |     | NULL              |                   |
| timestamp | timestamp    | NO   |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+-----------+--------------+------+-----+-------------------+-------------------+

```

<span aria-hidden="true" id="creating-our-template"></span>

## Creating our Template

We're only going to create a basic Template, but feel free to expand on it for your own use case.

```json
{
  "steps": {
    ":original": {
      "robot": "/upload/handle"
    },
    "resized": {
      "robot": "/image/resize",
      "use": ":original",
      "width": 500,
      "format": "jpeg",
      "resize_strategy": "fit",
      "imagemagick_stack": "{{stacks.imagemagick.recommended_version}}"
    }
  },
  "notify_url": "${fields.url}"
}

```

Our image is resized to 500px wide before sending a response to the `notify_url` provided by the field. Our field value has been set to `window.location.href`, which is convenient when using a tunnel URL. If you use `@transloadit/notify-url-relay`, you can instead set this directly to your local callback URL (for example `http://127.0.0.1:8000`). If your PHP will be hosted elsewhere on your site than the Robodog component, you should change this URL.

Make sure to copy the Template ID and paste it into the Robodog component as the`template_id`.

<span aria-hidden="true" id="exposing-local-notifications-during-development"></span>

## Exposing local Notifications during development

For local notification reachability, use[Cloudflare Tunnel⁠](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/),[ngrok⁠](https://dashboard.ngrok.com/get-started/setup), or the first-party[@transloadit/notify-url-relay⁠](https://www.npmjs.com/package/@transloadit/notify-url-relay) via`npx -y @transloadit/notify-url-relay` (relay differs from tunnels by polling public status and forwarding terminal notifications to your local `notify_url`), and in this walkthrough we'll use the first-party relay.

To start a local server, we run the following command:

```bash
php -S localhost:8000

```

Run the first-party relay:

```bash
TRANSLOADIT_SECRET=******** npx -y @transloadit/notify-url-relay \
  --notifyUrl "http://127.0.0.1:8000" \
  --log-level info

```

When using the relay, point your app/SDK Transloadit endpoint to `http://127.0.0.1:8888`.

If you prefer a tunnel instead, use Cloudflare Tunnel or ngrok and keep `window.location.href` as the callback URL source.

Now, if you go to your local URL, you should see the Robodog Dashboard.

<span aria-hidden="true" id="connecting-to-our-database"></span>

## Connecting to our database

The very first thing we need to do with PHP is create a link with our MySQL database. Inside of`index.php`, insert the following code:

```php
<?php
$link = mysqli_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD', 'transloadit');

// Check connection
if ($link === false) {
  die('ERROR: Could not connect. ' . mysqli_connect_error());
}
?>

```

<span aria-hidden="true" id="adding-data-to-the-database"></span>

## Adding data to the database

Of course, when we receive our notification pingback, we'll want to add some of the information to our database. I've cherry-picked a few fields, but you should customize them to your own preferences.

```sql
INSERT INTO assemblies (id, ok, http_code)
VALUES ('{$transloadit['assembly_id']}', '{$transloadit['ok']}', '{$transloadit['http_code']}');

```

We can use the global `$_POST` variable to populate our JSON when we receive a response.

```php
<?php
$transloadit = 'No response data yet! :)';

//Add to database
if (isset($_POST['transloadit'])) {
  $json = $_POST['transloadit'];
  $transloadit = json_decode($json, true);

  // The resulting files can be found inside $transloadit['results'] now.
  // Depending on your integration, you may want to
  // save references to these in your database as well.

  // Attempt insert query execution
  $sql = "INSERT INTO assemblies (id, ok, http_code) VALUES ('{$transloadit['assembly_id']}', '{$transloadit['ok']}', '{$transloadit['http_code']}')";
  if (mysqli_query($link, $sql)) {
    echo 'Records inserted successfully.';
  } else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
}
?>

```

<span aria-hidden="true" id="retrieving-data-from-the-database"></span>

## Retrieving data from the database

To get some feedback and make sure everything is working correctly, let's pull the five most recentAssemblies from our database and display them on our website.

Here's the SQL statement we'll use:

```sql
SELECT id,ok,timestamp
FROM assemblies
ORDER BY timestamp DESC
LIMIT 5;

```

Which we can query and display within our PHP:

```php
<?pgp
// Retrieves five most recent assemblies
$sql = 'SELECT id,ok,timestamp FROM assemblies ORDER BY timestamp DESC LIMIT 5';
$result = mysqli_query($link, $sql);

if ($result->num_rows > 0) {
  // Output the data from each row
  while ($row = $result->fetch_assoc()) {
    echo 'ID: ' .
      $row['id'] .
      ' - OK: ' .
      $row['ok'] .
      ' - TIMESTAMP: ' .
      $row['timestamp'] .
      '<br>';
  }
} else {
  echo '0 results';
}
?>

```

<span aria-hidden="true" id="testing"></span>

## Testing

If you run a few images through the Robodog Dashboard and then refresh the page, you should see a list of Assemblies similar to the one below, indicating that everything is in working order.

```plaintext
ID: 1a8da2d953014362ae7aaf9b1a0a94e1 - OK: ASSEMBLY_COMPLETED - TIMESTAMP: 2021-07-13 12:55:36
ID: ea39c16274d74ff6a6302cf26ce85ee1 - OK: ASSEMBLY_COMPLETED - TIMESTAMP: 2021-07-13 12:39:45
ID: 59bf7ff2c6dc4491a5867125a95d3ee1 - OK: ASSEMBLY_COMPLETED - TIMESTAMP: 2021-07-13 12:39:40
ID: 356250064e1040acb7b3cd70bf1da9e1 - OK: ASSEMBLY_COMPLETED - TIMESTAMP: 2021-07-13 12:39:34
ID: 945161b4de994525aa680614422de5e1 - OK: ASSEMBLY_COMPLETED - TIMESTAMP: 2021-07-13 12:39:28

```

<span aria-hidden="true" id="finishing-up"></span>

## Finishing up

Hopefully, this blog has piqued your interest in using Transloadit asynchronously, and you've come up with some ideas for how to take it a step further to supercharge your next project ⚡

[#walkthrough](/blog/tags/walkthrough.md)[#assembly](/blog/tags/assembly.md)[#php](/blog/tags/php.md)[#api](/blog/tags/api.md)[#uppy](/blog/tags/uppy.md)

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed · 5 GB included in the free plan

Cancel anytime
