phpffmpegapilaravel

How to Use FFmpeg with PHP (No Installation Required)

··11 min read
How to Use FFmpeg with PHP (No Installation Required)

You need to process video in your PHP application: resize uploads, convert formats, pull thumbnails, or cut social clips out of user content. Search "php ffmpeg" and every result tells you to install the FFmpeg binary on your server and call it with exec(). That works on your laptop and falls apart the moment you deploy.

Quick answer: No FFmpeg installation is required to use FFmpeg with PHP: no binary, no server, no exec(). The common route is installing the FFmpeg binary on the server and shelling out with exec("ffmpeg -i in.mp4 out.mp4"), which works locally but breaks on shared hosting, on Laravel Vapor, and anywhere exec() is disabled. The alternative is to send the job to a cloud FFmpeg API in one HTTP request: FFmpeg Micro accepts the same FFmpeg options over REST from cURL, Guzzle, or its official PHP SDK on PHP 8.1+ (composer require ffmpeg-micro/ffmpeg-micro-php), so you get transcoding, resizing, and thumbnails with no binary to install and no servers to run.

Why the exec() approach breaks in production

Shelling out to the FFmpeg binary is the approach almost every PHP tutorial teaches, and it's the one that fails first:

$input = escapeshellarg("/path/to/input.mp4");
$output = escapeshellarg("/path/to/output.mp4");

exec("ffmpeg -i {$input} -c:v libx264 -crf 23 {$output} 2>&1", $out, $code);

if ($code !== 0) {
    throw new RuntimeException("FFmpeg failed: " . implode("\n", $out));
}

On a dev machine with Homebrew FFmpeg installed, that's fine. In production you hit one of these:

  • Shared hosting almost never ships FFmpeg, and you can't install it.
  • exec() is disabled by disable_functions on a lot of hosts.
  • Laravel Forge and plain VPS setups need manual FFmpeg installs, per server, forever.
  • Serverless PHP (Laravel Vapor, Vercel) has no persistent filesystem to keep a 70 MB static build in.
  • You own the codec updates, the security patches, and the disk space for temp files.

A 10-minute 1080p transcode also pins a CPU core for minutes. If that runs inside a PHP-FPM worker, the worker is gone for the duration and your request times out at 30 or 60 seconds.

What php-ffmpeg actually gives you

PHP-FFmpeg is an object-oriented wrapper around the same binary, so it changes the syntax and not the deployment problem:

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open("input.mp4");

$video->filters()->resize(new FFMpeg\Coordinate\Dimension(1280, 720));
$video->save(new FFMpeg\Format\Video\X264(), "output.mp4");

Nicer to read. It still calls ffmpeg and ffprobe on the local machine, still needs both binaries on PATH, and still blocks the PHP process while the encode runs. If exec() is disabled, PHP-FFmpeg can't work either.

Comparing the three ways to run FFmpeg from PHP

Picking between exec(), php-ffmpeg, and a cloud FFmpeg API comes down to who installs and babysits the encoder. The three options differ on the things that bite in production:

`exec()`php-ffmpegFFmpeg Micro API
Needs the binary installedYesYesNo
Works with `exec()` disabledNoNoYes
Works on shared hostingRarelyRarelyYes
Blocks the PHP workerYesYesNo, jobs are async
Who patches the codecsYouYouManaged
Minimum PHPAny8.0+7.4 with cURL, 8.1 with the SDK

Sending a transcode job from PHP

FFmpeg Micro runs FFmpeg as a hosted job queue: you submit a job, poll its status, then download the output. The only PHP requirement is the cURL extension, which virtually every host enables by default. That makes it the one option on the table for shared hosting and serverless PHP, where installing a binary isn't something you're allowed to do. The API overview covers the full job model.

With PHP's built-in cURL and no dependencies at all:

$apiKey = getenv("FFMPEG_MICRO_API_KEY");

$ch = curl_init("https://api.ffmpeg-micro.com/v1/transcodes");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . $apiKey,
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "inputs" => [["url" => "https://example.com/video.mp4"]],
        "outputFormat" => "mp4",
        "preset" => ["quality" => "high", "resolution" => "1080p"],
    ]),
    CURLOPT_RETURNTRANSFER => true,
]);

$response = json_decode(curl_exec($ch), true);

echo "Job ID: " . $response["id"];

Note what isn't there: no curl_close(). That function has done nothing since PHP 8.0, when cURL handles became objects, and on PHP 8.5 calling it emits a deprecation warning. Delete it from old code.

If you're in Laravel or anything else that already ships Guzzle:

use GuzzleHttp\Client;

$client = new Client([
    "base_uri" => "https://api.ffmpeg-micro.com",
    "headers" => ["Authorization" => "Bearer " . $apiKey],
]);

$response = $client->post("/v1/transcodes", [
    "json" => [
        "inputs" => [["url" => "https://example.com/video.mp4"]],
        "outputFormat" => "mp4",
        "preset" => ["quality" => "high", "resolution" => "1080p"],
    ],
]);

$job = json_decode($response->getBody(), true);
echo "Job ID: " . $job["id"];

Both requests send identical JSON. Field names are camelCase (outputFormat), and inputs is always an array of objects with a url key, even for a single file.

Polling for status and downloading the result

A transcode job returns one of five statuses: pending, processing, completed, failed, or canceled. Poll while it's pending or processing, then check what you actually got:

$jobId = $job["id"];

do {
    sleep(2);
    $ch = curl_init("https://api.ffmpeg-micro.com/v1/transcodes/{$jobId}");
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $apiKey],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $status = json_decode(curl_exec($ch), true);
} while (in_array($status["status"], ["pending", "processing"], true));

if ($status["status"] !== "completed") {
    throw new RuntimeException("Job ended as " . $status["status"]);
}

$ch = curl_init("https://api.ffmpeg-micro.com/v1/transcodes/{$jobId}/download");
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $apiKey],
    CURLOPT_RETURNTRANSFER => true,
]);
$download = json_decode(curl_exec($ch), true);

echo "Download: " . $download["url"];

The download endpoint returns a signed URL valid for 10 minutes. Stream it to your own storage inside that window, or redirect the user straight to it. Status checks and downloads are free, so a 2-second poll costs you nothing but a little latency.

Official PHP SDK

FFmpeg Micro publishes a PHP SDK that wraps every endpoint, so you can skip the hand-rolled HTTP code:

composer require ffmpeg-micro/ffmpeg-micro-php

It needs PHP 8.1 or later. The package is on Packagist, and the source and full method docs are on GitHub. It's generated from the API's OpenAPI spec, so it covers transcodes, uploads, transcription, and blueprints, and it hands back typed objects instead of nested arrays. Method names follow the route: v1TranscodesPost is POST /v1/transcodes. Failed calls throw FFmpegMicro\ApiException, where getCode() is the HTTP status and getResponseBody() is the API's error payload.

The whole submit-poll-download cycle fits in a screen:

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

use FFmpegMicro\Api\DefaultApi;
use FFmpegMicro\Configuration;
use FFmpegMicro\Model\CreateTranscodeRequest;

$config = Configuration::getDefaultConfiguration()
    ->setAccessToken(getenv("FFMPEG_MICRO_API_KEY"));
$api = new DefaultApi(new GuzzleHttp\Client(), $config);

$job = $api->v1TranscodesPost(new CreateTranscodeRequest([
    "inputs" => [["url" => "https://example.com/video.mp4"]],
    "outputFormat" => "mp4",
    "preset" => ["quality" => "high", "resolution" => "1080p"],
]));

do {
    sleep(2);
    $job = $api->v1TranscodesIdGet($job->getId());
} while (in_array($job->getStatus(), ["pending", "processing"], true));

if ($job->getStatus() !== "completed") {
    throw new RuntimeException("Job ended as " . $job->getStatus());
}

echo $api->v1TranscodesIdDownloadGet($job->getId())->getUrl();

If you're stuck on PHP 7.4 or 8.0, use the cURL or Guzzle examples above. They call the same endpoints with the same payloads.

Passing raw FFmpeg options

Presets handle the common cases, and the API also accepts raw FFmpeg flags when you need exact control over the encode:

$response = $client->post("/v1/transcodes", [
    "json" => [
        "inputs" => [["url" => "https://example.com/video.mp4"]],
        "outputFormat" => "webm",
        "options" => [
            ["option" => "-c:v", "argument" => "libvpx-vp9"],
            ["option" => "-crf", "argument" => "30"],
            ["option" => "-b:v", "argument" => "0"],
            ["option" => "-c:a", "argument" => "libopus"],
        ],
    ],
]);

Each entry is an {option, argument} object, so the flags you'd type on the command line carry over one for one. That request converts MP4 to WebM with VP9 video and Opus audio, the same as ffmpeg -i in.mp4 -c:v libvpx-vp9 -crf 30 -b:v 0 -c:a libopus out.webm.

Uploading a local file first

If the video isn't already at a public URL, upload it in three steps before you transcode:

// Step 1: Get a presigned upload URL
$presign = $client->post("/v1/upload/presigned-url", [
    "json" => [
        "filename" => "my-video.mp4",
        "contentType" => "video/mp4",
        "fileSize" => filesize("/path/to/my-video.mp4"),
    ],
]);
$presignData = json_decode($presign->getBody(), true);

// Step 2: Upload straight to cloud storage
$uploadClient = new Client();
$uploadClient->put($presignData["result"]["uploadUrl"], [
    "headers" => ["Content-Type" => "video/mp4"],
    "body" => fopen("/path/to/my-video.mp4", "r"),
]);

// Step 3: Confirm the upload
$confirm = $client->post("/v1/upload/confirm", [
    "json" => [
        "filename" => $presignData["result"]["filename"],
        "fileSize" => filesize("/path/to/my-video.mp4"),
    ],
]);
$confirmData = json_decode($confirm->getBody(), true);

$fileUrl = $confirmData["result"]["fileUrl"];

The upload endpoints wrap their response in a result object, unlike the transcode endpoints, which return id, status, and url at the top level.

Pass $fileUrl as the url of your transcode job's input. Because step 2 goes directly to storage, the bytes never pass through your PHP process, which is what keeps this working on hosts with a 20 MB upload_max_filesize.

When this is the wrong fit

An API call is not free of trade-offs, and there are cases where keeping FFmpeg local is the better call. If you already run dedicated encode boxes with spare CPU and your volume is steady, a self-hosted binary is cheaper per minute than any metered service. If your source files never leave a private network for compliance reasons, uploading them to cloud storage may not be an option you have. And on the free tier the input cap is 100 MB per file, which rises to 1,024 MB on every paid plan, so very large masters need a paid plan or a local pre-trim.

Don't run even a cloud transcode synchronously inside a web request for anything longer than a short clip. Submit the job, return a 202, and poll from a Laravel queue worker or a cron task. The job survives your request; the request won't survive the job.

Common pitfalls

A handful of mistakes turn a working PHP snippet into a support ticket:

  • Reaching for file_get_contents with a stream context instead of cURL or Guzzle. Custom headers and POST bodies get awkward fast, and many hosts disable allow_url_fopen.
  • Posting form-encoded data. The API expects a JSON body, so set Content-Type: application/json and run your payload through json_encode.
  • Looping only on completed. A job that ends failed or canceled will spin forever if your condition is "not completed yet", so check the terminal status after the loop.
  • Polling every 100 milliseconds. Two seconds is plenty, and tight polling just burns your own PHP worker.
  • Hardcoding the API key. Read it from the environment: config("services.ffmpeg_micro.key") in Laravel, getenv("FFMPEG_MICRO_API_KEY") in plain PHP.
  • Assuming the download URL is permanent. It expires after 10 minutes, so fetch the file or copy it to your own bucket in the same job run.

FAQ

Does this work on shared hosting?

Yes, the API approach works on shared hosting because it needs nothing but PHP's cURL extension. There's no FFmpeg binary to install, no exec() call, and no special server permissions involved.

What PHP version do I need?

The cURL and Guzzle examples in this guide run on PHP 7.4 or later. The official FFmpeg Micro PHP SDK requires PHP 8.1 or later, so if you're on an older version, use the raw HTTP examples against the same endpoints.

Is there an official PHP SDK?

Yes. Install it with composer require ffmpeg-micro/ffmpeg-micro-php. It needs PHP 8.1 or later, covers every endpoint including transcodes, uploads, transcription, and blueprints, and returns typed objects. On older PHP, the cURL and Guzzle examples call the same API.

How much does FFmpeg Micro cost?

FFmpeg Micro bills on the duration of the video processed, metered per second with no rounding up to the minute, and failed jobs are never billed. One token buys 10 seconds of input video, so a 5-minute clip costs 30 tokens. Trim 30 seconds out of a one-hour recording and you're billed for 30 seconds. Current plans and top-up bundles are on the pricing page.

What video formats are supported?

Output formats cover video (MP4, WebM, MOV, AVI), audio (MP3, M4A, AAC, WAV, OGG, Opus, FLAC), and images (JPEG, PNG, GIF, WebP) for thumbnails and still frames. For frame extraction specifically, see the thumbnail guide, and for pulling audio tracks out of video, the extract audio recipe.

The free tier needs no card: a new account gets 200 tokens, about 33 minutes of input video, plus API access, unlimited API keys, and unlimited storage. Sign up free and the dashboard quickstart issues a temporary key and runs a presigned upload, a transcode, and a download for you, so you can confirm the flow before you write the PHP.

*Last verified: October 2026. API examples tested against the FFmpeg Micro v1 API (FFmpeg 7.0.2), the cURL and Guzzle examples on PHP 7.4.33 with Guzzle 7.16.0, the SDK example with ffmpeg-micro/ffmpeg-micro-php v0.1.0, the php-ffmpeg example with php-ffmpeg/php-ffmpeg v1.4.0 on PHP 8.4 (ffmpeg 7.1.5), and the ffmpeg CLI commands with ffmpeg 8.0.1.*

About Javid Jamae

Founder & CEO at FFmpeg Micro

Javid is a software engineer, author, and entrepreneur with over 25 years of professional software development experience across enterprise, startup, and consulting environments. He founded FFmpeg Micro to make video processing accessible to developers through a simple, automation-first REST API.

Software EngineeringVideo ProcessingFFmpegCloud ArchitectureAPI DesignAutomation

Ready to process videos at scale?

Start using FFmpeg Micro's simple API today. No infrastructure required.

Get Started Free