SUPPORT.TWILIO.COM END OF LIFE NOTICE: This site, support.twilio.com, is scheduled to go End of Life on February 27, 2024. All Twilio Support content has been migrated to help.twilio.com, where you can continue to find helpful Support articles, API docs, and Twilio blog content, and escalate your issues to our Support team. We encourage you to update your bookmarks and begin using the new site today for all your Twilio Support needs.

How can I download an MMS or WhatsApp media file with PHP?

When Twilio receives an MMS or WhatsApp message with a media file, you can download the file manually from the Messaging Logs in Console, or programatically. This guide explains how to create a PHP application for downloading files received via MMS messages.

Overview

Our sample script for downloading a Twilio MMS or WhatsApp media file with PHP takes the media file's URL as an input, along with the desired destination file name for saving it. This script will then perform an HTTP request to the Twilio API, retrieve the media file, and save it on your local disk.

Note: PHP typically uses the cURL library under the hood to make HTTP requests. If you don't already have this library, you may need to install it in your PHP environment to make this script work.

Sample code

Below you will find a sample PHP script that retrieves an MMS media file, renames it, and saves it to your local disk.

<?php

class HTTPRequester {
public function getMediaContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Option to follow the redirects, otherwise it will return an XML
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$media = curl_exec($ch);
curl_close($ch);
return $media;
}
}

echo "+++ Start.\xA";

// store your MMS Media URL here
$mmsMedia = 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media/MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// store the name you want to use for your downloaded file here
$mmsMediaFilenameWrite = "httpsMmsMediaUrl.jpg";

$http = new HTTPRequester();
$mmsFileContent = $http->getMediaContent($mmsMedia);
$mmsFileWrite = fopen($mmsMediaFilenameWrite, 'w');
fwrite($mmsFileWrite, $mmsFileContent);

echo "+++ Exit.\xA";

This example will save the MMS media file to the local disk.

To make this script work for you, make the following updates:

  • Set $mmsMedia your MMS media URL. The MMS URL media can be obtained from the Twilio Console Messaging Logs or from the the value of MediaUrl0, from an inbound webhook HTTP request. This will contain your Twilio Account SID starting with AC, the Message SID starting with MM, and the Media SID starting with ME.
  • Set $mmsMediaFilenameWrite to the desired local filename you would like the media file saved as.
Have more questions? Submit a request
Powered by Zendesk