Search code examples
phptwiliotwilio-apitwilio-php

How to download media in Twilio Whatsapp using PHP?


So I am using Twilio Whatsapp API and need to down load media using PHP. I can pickup the https://api.twilio..... address that reroutes to an aws address - therefore downloading using the below code wont work as it tries to download from the api.twilio URL and not the aws address that its routed to:

 $url = $URLFile;
    
    
    // Initialize the cURL session
    $ch = curl_init($url);
    
    // Initialize directory name where
    // file will be save
    // $dir = './';
    $dir = $dirname;
    
    // Use basename() function to return
    // the base name of file
    $file_name = basename($url);
    
    // Save file into file location
    $save_file_loc = $dir . $file_name;
    
    // Open file
    $fp = fopen($save_file_loc, 'wb');
    
    // It set an option for a cURL transfer
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    
    // Perform a cURL session
    curl_exec($ch);
    
    // Closes a cURL session and frees all resources
    curl_close($ch);
    
    // Close file
    fclose($fp);

Solution

  • You'll want to use CURLOPT_FOLLOWLOCATION to follow redirects with cURL.

    You can do this:

     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    and your code will follow the redirect.