phptwiliomms

Save File From URL that has a redirection


I am trying to save a local copy of all the media that is sent through Twilio.

$media = file_get_contents($mediaUrl);
$filename = $mediaSid . '.' . $fileExtension;
file_put_contents(public_path('storage/mms/' . $filename), $media);

The problem is file_get_contents does not seem to be following the redirection so I get a file that contains TwiML. I have an example below of what I keep getting. My question is what function do I need to use so that it follows the redirection and I get the actual data of the media rather than the XML?

The file that is created:

<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse><Media><Sid/><AccountSid>AC....</AccountSid><ParentSid/><ContentType/><DateCreated>Fri, 08 Nov 2019 01:49:02 +0000</DateCreated><DateUpdated>Fri, 08 Nov 2019 01:49:02 +0000</DateUpdated><Uri>/2010-04-01/Accounts/AC.../Messages/MM.../Media/ME...</Uri></Media></TwilioResponse>

Solution

  • It is recommended to use libcurl rather than file_get_contents to work around this particular issue, according to Twilio support.

    The reason for this is the Twilio sends a temporary URL which is over 1024 characters and is just ignored.

    $mediaUrl = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxx/Messages/MMxxxxxxxxxxx/Media/MExxxxxxxxxxxxx";
    
    $accountSid = "ACxxxxxxxxxxxxxxx";
    $authToken = "...";
    
    $curl = curl_init();
    $outfile = fopen('temp.jpg', 'w+');
    $options = array(
        CURLOPT_HTTPGET => true,
        CURLOPT_URL => $mediaUrl,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD => "$accountSid:$authToken",
        CURLOPT_FILE => $outfile
    );
    curl_setopt_array($curl, $options);
    curl_exec($curl);
    curl_close($curl);