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 ofMediaUrl0
, from an inbound webhook HTTP request. This will contain your Twilio Account SID starting withAC
, the Message SID starting withMM
, and the Media SID starting withME
. - Set
$mmsMediaFilenameWrite
to the desired local filename you would like the media file saved as.