You know how to receive and reply to incoming SMS messages. What if you receive an MMS message containing an image you'd like to download? Let's learn how we can grab that image and any other incoming MMS media using PHP and Laravel.
When Twilio receives a message for your phone number, it can make an HTTP call to a webhook that you create. The easiest way to handle HTTP requests with PHP is to use Laravel or a similar framework.
Twilio expects, at the very least, for your webhook to return a 200 OK
response if everything is peachy. Often, however, you will return some TwiML in your response as well. TwiML is just a set of XML commands telling Twilio how you'd like it to respond to your message. Rather than manually generating the XML, we'll use the Twilio\Twiml
module in the helper library that can make generating the TwiML and the rest of the webhook plumbing easy peasy.
To install the library, run:
_10composer install twilio/sdk
Add a new controller called MessagingController that handles an incoming SMS request.
_109<?php_109_109namespace App\Http\Controllers;_109_109use App\Http\Controllers\Controller;_109use App\MMSMedia;_109use App\Services\MediaMessageService\IMediaMessageService;_109use Illuminate\Foundation\Auth\AuthenticatesUsers;_109use Illuminate\Http\Request;_109use Illuminate\Http\Response;_109use Magyarjeti\MimeTypes\MimeTypeConverter;_109use Twilio\Rest\Client;_109use Twilio\Twiml;_109_109class MessagingController extends Controller_109{_109 /*_109 |--------------------------------------------------------------------------_109 | Messaging Controller_109 |--------------------------------------------------------------------------_109 |_109 | This controller receives messages from Twilio and makes the media available_109 | via the /images url._109 */_109_109 protected $twilio;_109 protected $accountSid;_109 protected $twilioNumber;_109 /**_109 * Create a new controller instance._109 *_109 * @return void_109 */_109 public function __construct()_109 {_109 $this->accountSid = env('TWILIO_ACCOUNT_SID');_109 $this->twilioNumber = env('TWILIO_NUMBER');_109 $authToken = env('TWILIO_AUTH_TOKEN');_109_109 $this->twilio = new Client($this->accountSid, $authToken);_109 }_109_109 public function handleIncomingSMS(Request $request, IMediaMessageService $mediaService)_109 {_109 $converter = new MimeTypeConverter;_109 $NumMedia = (int)$request->input('NumMedia');_109 $FromNumber = $request->input('From');_109 $MessageSid = $request->input('MessageSid');_109_109 for ($i=0; $i < $NumMedia; $i++) {_109 $mediaUrl = $request->input("MediaUrl$i");_109 $MIMEType = $request->input("MediaContentType$i");_109 $fileExtension = $converter->toExtension($MIMEType);_109 $mediaSid = basename($mediaUrl);_109_109 $media = $mediaService->getMediaContent($mediaUrl);_109_109 $filename = "$mediaSid.$fileExtension";_109_109 $mediaData = compact('mediaSid', 'MessageSid', 'mediaUrl', 'media', 'filename', 'MIMEType');_109 $mmsMedia = new MMSMedia($mediaData);_109 $mmsMedia->save();_109 }_109_109 $response = new Twiml();_109 $messageBody = $NumMedia == 0 ? 'Send us an image!' : "Thanks for the $NumMedia images.";_109 $message = $response->message([_109 'from' => $request->input('To'),_109 'to' => $FromNumber_109 ]);_109 $message->body($messageBody);_109_109 return (string)$response;_109 }_109_109 public function deleteMediaFromTwilio($mediaItem)_109 {_109 return $this->twilio->api->accounts($this->accountSid)_109 ->messages($mediaItem['MessageSid'])_109 ->media($mediaItem['mediaSid'])_109 ->delete();_109 }_109_109 public function allMedia()_109 {_109 $mediaItems = MMSMedia::all();_109 return $mediaItems;_109 }_109_109 public function getMediaFile($filename, Response $response)_109 {_109 $media = MMSMedia::where('filename', $filename)->firstOrFail();_109 $fileContents = $media['media'];_109 $MessageSid = $media['MessageSid'];_109 $mediaSid = $media['mediaSid'];_109 $MIMEType = $media['MIMEType'];_109_109 $media->delete();_109 $this->deleteMediaFromTwilio(compact('mediaSid', 'MessageSid'));_109_109 return response($fileContents, 200)_109 ->header('Content-Type', $MIMEType);_109 }_109_109 public function config()_109 {_109 return ['twilioNumber' => $this->twilioNumber];_109 }_109}
When Twilio calls your webhook, it sends a number of parameters about the message you just received. Most of these, such as the To
phone number, the From
phone number, and the Body
of the message are available as properties of the request body.
Since an MMS message can have multiple attachments, Twilio will send us form variables named MediaUrlX
, where X is a zero-based index. So, for example, the URL for the first media attachment will be in the MediaUrl0
parameter, the second in MediaUrl1
, and so on.
In order to handle a dynamic number of attachments, we pull the URLs out of the body request like this:
_109<?php_109_109namespace App\Http\Controllers;_109_109use App\Http\Controllers\Controller;_109use App\MMSMedia;_109use App\Services\MediaMessageService\IMediaMessageService;_109use Illuminate\Foundation\Auth\AuthenticatesUsers;_109use Illuminate\Http\Request;_109use Illuminate\Http\Response;_109use Magyarjeti\MimeTypes\MimeTypeConverter;_109use Twilio\Rest\Client;_109use Twilio\Twiml;_109_109class MessagingController extends Controller_109{_109 /*_109 |--------------------------------------------------------------------------_109 | Messaging Controller_109 |--------------------------------------------------------------------------_109 |_109 | This controller receives messages from Twilio and makes the media available_109 | via the /images url._109 */_109_109 protected $twilio;_109 protected $accountSid;_109 protected $twilioNumber;_109 /**_109 * Create a new controller instance._109 *_109 * @return void_109 */_109 public function __construct()_109 {_109 $this->accountSid = env('TWILIO_ACCOUNT_SID');_109 $this->twilioNumber = env('TWILIO_NUMBER');_109 $authToken = env('TWILIO_AUTH_TOKEN');_109_109 $this->twilio = new Client($this->accountSid, $authToken);_109 }_109_109 public function handleIncomingSMS(Request $request, IMediaMessageService $mediaService)_109 {_109 $converter = new MimeTypeConverter;_109 $NumMedia = (int)$request->input('NumMedia');_109 $FromNumber = $request->input('From');_109 $MessageSid = $request->input('MessageSid');_109_109 for ($i=0; $i < $NumMedia; $i++) {_109 $mediaUrl = $request->input("MediaUrl$i");_109 $MIMEType = $request->input("MediaContentType$i");_109 $fileExtension = $converter->toExtension($MIMEType);_109 $mediaSid = basename($mediaUrl);_109_109 $media = $mediaService->getMediaContent($mediaUrl);_109_109 $filename = "$mediaSid.$fileExtension";_109_109 $mediaData = compact('mediaSid', 'MessageSid', 'mediaUrl', 'media', 'filename', 'MIMEType');_109 $mmsMedia = new MMSMedia($mediaData);_109 $mmsMedia->save();_109 }_109_109 $response = new Twiml();_109 $messageBody = $NumMedia == 0 ? 'Send us an image!' : "Thanks for the $NumMedia images.";_109 $message = $response->message([_109 'from' => $request->input('To'),_109 'to' => $FromNumber_109 ]);_109 $message->body($messageBody);_109_109 return (string)$response;_109 }_109_109 public function deleteMediaFromTwilio($mediaItem)_109 {_109 return $this->twilio->api->accounts($this->accountSid)_109 ->messages($mediaItem['MessageSid'])_109 ->media($mediaItem['mediaSid'])_109 ->delete();_109 }_109_109 public function allMedia()_109 {_109 $mediaItems = MMSMedia::all();_109 return $mediaItems;_109 }_109_109 public function getMediaFile($filename, Response $response)_109 {_109 $media = MMSMedia::where('filename', $filename)->firstOrFail();_109 $fileContents = $media['media'];_109 $MessageSid = $media['MessageSid'];_109 $mediaSid = $media['mediaSid'];_109 $MIMEType = $media['MIMEType'];_109_109 $media->delete();_109 $this->deleteMediaFromTwilio(compact('mediaSid', 'MessageSid'));_109_109 return response($fileContents, 200)_109 ->header('Content-Type', $MIMEType);_109 }_109_109 public function config()_109 {_109 return ['twilioNumber' => $this->twilioNumber];_109 }_109}
Attachments to MMS messages can be of many different file types. JPG and GIF images, as well as MP4 and 3GP files, are all common. Twilio handles the determination of the file type for you and you can get the standard mime type from the MediaContentTypeX
parameter. If you are expecting photos, then you will likely see a lot of attachments with the mime type image/jpeg
.
_109<?php_109_109namespace App\Http\Controllers;_109_109use App\Http\Controllers\Controller;_109use App\MMSMedia;_109use App\Services\MediaMessageService\IMediaMessageService;_109use Illuminate\Foundation\Auth\AuthenticatesUsers;_109use Illuminate\Http\Request;_109use Illuminate\Http\Response;_109use Magyarjeti\MimeTypes\MimeTypeConverter;_109use Twilio\Rest\Client;_109use Twilio\Twiml;_109_109class MessagingController extends Controller_109{_109 /*_109 |--------------------------------------------------------------------------_109 | Messaging Controller_109 |--------------------------------------------------------------------------_109 |_109 | This controller receives messages from Twilio and makes the media available_109 | via the /images url._109 */_109_109 protected $twilio;_109 protected $accountSid;_109 protected $twilioNumber;_109 /**_109 * Create a new controller instance._109 *_109 * @return void_109 */_109 public function __construct()_109 {_109 $this->accountSid = env('TWILIO_ACCOUNT_SID');_109 $this->twilioNumber = env('TWILIO_NUMBER');_109 $authToken = env('TWILIO_AUTH_TOKEN');_109_109 $this->twilio = new Client($this->accountSid, $authToken);_109 }_109_109 public function handleIncomingSMS(Request $request, IMediaMessageService $mediaService)_109 {_109 $converter = new MimeTypeConverter;_109 $NumMedia = (int)$request->input('NumMedia');_109 $FromNumber = $request->input('From');_109 $MessageSid = $request->input('MessageSid');_109_109 for ($i=0; $i < $NumMedia; $i++) {_109 $mediaUrl = $request->input("MediaUrl$i");_109 $MIMEType = $request->input("MediaContentType$i");_109 $fileExtension = $converter->toExtension($MIMEType);_109 $mediaSid = basename($mediaUrl);_109_109 $media = $mediaService->getMediaContent($mediaUrl);_109_109 $filename = "$mediaSid.$fileExtension";_109_109 $mediaData = compact('mediaSid', 'MessageSid', 'mediaUrl', 'media', 'filename', 'MIMEType');_109 $mmsMedia = new MMSMedia($mediaData);_109 $mmsMedia->save();_109 }_109_109 $response = new Twiml();_109 $messageBody = $NumMedia == 0 ? 'Send us an image!' : "Thanks for the $NumMedia images.";_109 $message = $response->message([_109 'from' => $request->input('To'),_109 'to' => $FromNumber_109 ]);_109 $message->body($messageBody);_109_109 return (string)$response;_109 }_109_109 public function deleteMediaFromTwilio($mediaItem)_109 {_109 return $this->twilio->api->accounts($this->accountSid)_109 ->messages($mediaItem['MessageSid'])_109 ->media($mediaItem['mediaSid'])_109 ->delete();_109 }_109_109 public function allMedia()_109 {_109 $mediaItems = MMSMedia::all();_109 return $mediaItems;_109 }_109_109 public function getMediaFile($filename, Response $response)_109 {_109 $media = MMSMedia::where('filename', $filename)->firstOrFail();_109 $fileContents = $media['media'];_109 $MessageSid = $media['MessageSid'];_109 $mediaSid = $media['mediaSid'];_109 $MIMEType = $media['MIMEType'];_109_109 $media->delete();_109 $this->deleteMediaFromTwilio(compact('mediaSid', 'MessageSid'));_109_109 return response($fileContents, 200)_109 ->header('Content-Type', $MIMEType);_109 }_109_109 public function config()_109 {_109 return ['twilioNumber' => $this->twilioNumber];_109 }_109}
Depending on your use case, storing the URLs of the images (or videos or whatever) may be all you need. There are two key features to these URLs that make them very pliable for your use in your apps:
For example, if you are building a browser-based app that needs to display the images, all you need to do is drop an <img src="twilio url to your image">
tag into the page. If this works for you, then perhaps all you need is to store the URL in a database character field.
If you want to save the media attachments to a file, then you will need to make an HTTP request to the media URL and write the response stream to a file. If you need a unique filename, you can use the last part of the media URL. For example, suppose your media URL is the following:
_10https://api.twilio.com/2010-04-01/Accounts/ACxxxx/Messages/MMxxxx/Media/ME27be8a708784242c0daee207ff73db67
You can use that last part of the URL as a unique filename and look up the corresponding file extension for the mime type.
_109<?php_109_109namespace App\Http\Controllers;_109_109use App\Http\Controllers\Controller;_109use App\MMSMedia;_109use App\Services\MediaMessageService\IMediaMessageService;_109use Illuminate\Foundation\Auth\AuthenticatesUsers;_109use Illuminate\Http\Request;_109use Illuminate\Http\Response;_109use Magyarjeti\MimeTypes\MimeTypeConverter;_109use Twilio\Rest\Client;_109use Twilio\Twiml;_109_109class MessagingController extends Controller_109{_109 /*_109 |--------------------------------------------------------------------------_109 | Messaging Controller_109 |--------------------------------------------------------------------------_109 |_109 | This controller receives messages from Twilio and makes the media available_109 | via the /images url._109 */_109_109 protected $twilio;_109 protected $accountSid;_109 protected $twilioNumber;_109 /**_109 * Create a new controller instance._109 *_109 * @return void_109 */_109 public function __construct()_109 {_109 $this->accountSid = env('TWILIO_ACCOUNT_SID');_109 $this->twilioNumber = env('TWILIO_NUMBER');_109 $authToken = env('TWILIO_AUTH_TOKEN');_109_109 $this->twilio = new Client($this->accountSid, $authToken);_109 }_109_109 public function handleIncomingSMS(Request $request, IMediaMessageService $mediaService)_109 {_109 $converter = new MimeTypeConverter;_109 $NumMedia = (int)$request->input('NumMedia');_109 $FromNumber = $request->input('From');_109 $MessageSid = $request->input('MessageSid');_109_109 for ($i=0; $i < $NumMedia; $i++) {_109 $mediaUrl = $request->input("MediaUrl$i");_109 $MIMEType = $request->input("MediaContentType$i");_109 $fileExtension = $converter->toExtension($MIMEType);_109 $mediaSid = basename($mediaUrl);_109_109 $media = $mediaService->getMediaContent($mediaUrl);_109_109 $filename = "$mediaSid.$fileExtension";_109_109 $mediaData = compact('mediaSid', 'MessageSid', 'mediaUrl', 'media', 'filename', 'MIMEType');_109 $mmsMedia = new MMSMedia($mediaData);_109 $mmsMedia->save();_109 }_109_109 $response = new Twiml();_109 $messageBody = $NumMedia == 0 ? 'Send us an image!' : "Thanks for the $NumMedia images.";_109 $message = $response->message([_109 'from' => $request->input('To'),_109 'to' => $FromNumber_109 ]);_109 $message->body($messageBody);_109_109 return (string)$response;_109 }_109_109 public function deleteMediaFromTwilio($mediaItem)_109 {_109 return $this->twilio->api->accounts($this->accountSid)_109 ->messages($mediaItem['MessageSid'])_109 ->media($mediaItem['mediaSid'])_109 ->delete();_109 }_109_109 public function allMedia()_109 {_109 $mediaItems = MMSMedia::all();_109 return $mediaItems;_109 }_109_109 public function getMediaFile($filename, Response $response)_109 {_109 $media = MMSMedia::where('filename', $filename)->firstOrFail();_109 $fileContents = $media['media'];_109 $MessageSid = $media['MessageSid'];_109 $mediaSid = $media['mediaSid'];_109 $MIMEType = $media['MIMEType'];_109_109 $media->delete();_109 $this->deleteMediaFromTwilio(compact('mediaSid', 'MessageSid'));_109_109 return response($fileContents, 200)_109 ->header('Content-Type', $MIMEType);_109 }_109_109 public function config()_109 {_109 return ['twilioNumber' => $this->twilioNumber];_109 }_109}
Another idea for these image files could be uploading them to a cloud storage service like Azure Blob Storage or Amazon S3. You could also save them to a database, if necessary. They're just regular files at this point. Go crazy. In this case, we are saving them to the database in order to retrieve them later.
If you are downloading the attachments and no longer need them to be stored by Twilio, you can easily delete them. You can send an HTTP DELETE
request to the media URL, and it will be deleted, but you will need to be authenticated to do this. To make this easy, you can use the Twilio PHP Helper Library. As shown here:
_109<?php_109_109namespace App\Http\Controllers;_109_109use App\Http\Controllers\Controller;_109use App\MMSMedia;_109use App\Services\MediaMessageService\IMediaMessageService;_109use Illuminate\Foundation\Auth\AuthenticatesUsers;_109use Illuminate\Http\Request;_109use Illuminate\Http\Response;_109use Magyarjeti\MimeTypes\MimeTypeConverter;_109use Twilio\Rest\Client;_109use Twilio\Twiml;_109_109class MessagingController extends Controller_109{_109 /*_109 |--------------------------------------------------------------------------_109 | Messaging Controller_109 |--------------------------------------------------------------------------_109 |_109 | This controller receives messages from Twilio and makes the media available_109 | via the /images url._109 */_109_109 protected $twilio;_109 protected $accountSid;_109 protected $twilioNumber;_109 /**_109 * Create a new controller instance._109 *_109 * @return void_109 */_109 public function __construct()_109 {_109 $this->accountSid = env('TWILIO_ACCOUNT_SID');_109 $this->twilioNumber = env('TWILIO_NUMBER');_109 $authToken = env('TWILIO_AUTH_TOKEN');_109_109 $this->twilio = new Client($this->accountSid, $authToken);_109 }_109_109 public function handleIncomingSMS(Request $request, IMediaMessageService $mediaService)_109 {_109 $converter = new MimeTypeConverter;_109 $NumMedia = (int)$request->input('NumMedia');_109 $FromNumber = $request->input('From');_109 $MessageSid = $request->input('MessageSid');_109_109 for ($i=0; $i < $NumMedia; $i++) {_109 $mediaUrl = $request->input("MediaUrl$i");_109 $MIMEType = $request->input("MediaContentType$i");_109 $fileExtension = $converter->toExtension($MIMEType);_109 $mediaSid = basename($mediaUrl);_109_109 $media = $mediaService->getMediaContent($mediaUrl);_109_109 $filename = "$mediaSid.$fileExtension";_109_109 $mediaData = compact('mediaSid', 'MessageSid', 'mediaUrl', 'media', 'filename', 'MIMEType');_109 $mmsMedia = new MMSMedia($mediaData);_109 $mmsMedia->save();_109 }_109_109 $response = new Twiml();_109 $messageBody = $NumMedia == 0 ? 'Send us an image!' : "Thanks for the $NumMedia images.";_109 $message = $response->message([_109 'from' => $request->input('To'),_109 'to' => $FromNumber_109 ]);_109 $message->body($messageBody);_109_109 return (string)$response;_109 }_109_109 public function deleteMediaFromTwilio($mediaItem)_109 {_109 return $this->twilio->api->accounts($this->accountSid)_109 ->messages($mediaItem['MessageSid'])_109 ->media($mediaItem['mediaSid'])_109 ->delete();_109 }_109_109 public function allMedia()_109 {_109 $mediaItems = MMSMedia::all();_109 return $mediaItems;_109 }_109_109 public function getMediaFile($filename, Response $response)_109 {_109 $media = MMSMedia::where('filename', $filename)->firstOrFail();_109 $fileContents = $media['media'];_109 $MessageSid = $media['MessageSid'];_109 $mediaSid = $media['mediaSid'];_109 $MIMEType = $media['MIMEType'];_109_109 $media->delete();_109 $this->deleteMediaFromTwilio(compact('mediaSid', 'MessageSid'));_109_109 return response($fileContents, 200)_109 ->header('Content-Type', $MIMEType);_109 }_109_109 public function config()_109 {_109 return ['twilioNumber' => $this->twilioNumber];_109 }_109}
Twilio supports HTTP Basic and Digest Authentication. Authentication allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them. Learn more about HTTP authentication and validating incoming requests here.
All the code, in a complete working project, is available on GitHub. If you need to dig a bit deeper, you can head over to our API Reference and learn more about the Twilio webhook request and the REST API Media resource. Also, you will want to be aware of the pricing for storage of all the media files that you keep on Twilio's servers. For MMS media files, Storage, Unlimited free media storage.
We'd love to hear what you build with this.