Search code examples
phptwiliotwilio-php

Save a copy of any attachments included with an incoming SMS via Twilio


I successfully built a tool that uses Twilio voice and Text. It is used by my company to Send/Recive texts and test phone numbers. Unfortunately the only documentation for doing what I'd like to do is for Laravel (https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-download-images-incoming-mms-php-laravel). Then there is a very basic guide to SMS Attachments here (https://www.twilio.com/docs/sms/api/media-resource#list), unfortunately it doesnt go into detail.

$media = $twilio->messages($strSID)->media($strAttachmentSID)->fetch();

, but don't know what to do with the object it returns. I expect something simple like

$media = $twilio->messages($strSID)->media($strAttachmentSID)->fetch()->save();

Please help me understand what to do with the returned object.

I have tried using move_uploaded_file() on the uri returned by this object, but It didn't work.

I've tried sending a request using curl to the attachment url, but what it returns is given in the post for the incoming message.


Solution

  • Twilio developer evangelist here.

    When you receive a message which has media attached the incoming webhook request will have a parameter NumMedia which will tell you how many media objects there are. Then, for each of them, there will be MediaUrlX (where X is a number), which contains the URL of the media object, and MediaContentTypeX, which is the MIME type for the media object.

    In the laravel example, the content is downloaded with this function:

    
        public function getMediaContent($mediaUrl)
        {
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $mediaUrl);
          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;
        }
    

    Which you call with the media URL, e.g.

    $contents = getMediaContent($_POST["MediaUrl0"]);
    

    You would then need to save the contents to a file.

    Let me know if that helps at all.