You can easily import a file by its URL on your back end in PHP; here’s how.
Prerequisites
Composer: The PHP Package Manager
First, make sure you’ve got Composer installed on the system you’ll be playing with. Briefly, you can run the following on Mac/*NIX systems:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"
While it technically can run right there where it landed, it is strongly recommended that you move composer to a system-wide location:
mv composer.phar /usr/local/bin/composer
Windows users, why aren’t you using WSL? If you want a native Windows version of Composer, you can use the installer here: https://getcomposer.org/doc/00-intro.md#installation-windows
Look to https://getcomposer.org/ as the source of truth for that stuff.
Filestack’s PHP SDK
Install in the directory where you’ll be awesome:
$ composer require --prefer-dist filestack/filestack-php
Don’t type the dollar sign; that’s silly.
Code
Using the PHP SDK
If you’re in a framework such as Zend, CodeIgniter, Laravel, or Symfony, you’ll want to wire this up according to the framework’s tooling. If you’re just creating a one-off file to try this out, here’s the barebones import of the composer-require’d filestack-php package:
<?php require_once 'vendor/autoload.php'; use Filestack\FilestackClient; use Filestack\Filelink; use Filestack\FilestackException;
I’ll save that in a file called upload-url.php. Magic time.
Upload a file by URL
We’ve arrived at the moment of truth:
$filelink = null; $fileurl = 'https://c1.staticflickr.com/4/3258/2673143903_db2690e28f_b.jpg'; $client = new FilestackClient('MyAPIKEYwasHereBeforeIBlogged'); try { $filelink = $client->uploadUrl($fileurl); var_dump($filelink); } catch (FilestackException $e) { echo $e->getMessage(); echo $e->getCode(); }
Run this in a readable test by piping the output to less:
$ php upload-url.php | less
Got a mouse wheel? You can scroll through the output in less, or press the spacebar to go down a screenful. That’s right, science.
The part I’m really interested in is the file handle. I can see from the var_dump structure that I could access that by pulling out $filelink->handle after the upload completes. Cool! I’d store that, associate it with the user ID of the person (or bot) utilizing my app to make this kind of upload happen, and then later I can pull up all the file handles associated with my user and do more things.
David Liedle is Filestack’s Chief Evangelist. He works remotely in New York City with his wife and son, and their kitty. See more at https://DavidCanHelp.me/
Read More →