Breaking News
Home / Web / PHP / PHP Snippets / How to programatically download mp3 file from Web using PHP?

How to programatically download mp3 file from Web using PHP?

Code
Using PHP built in function fopen we can read a remote stream, read the contents in the buffer and flush it to the file.

  1. // Copy remote file locally
  2. $remote_file = ‘http://www.example.com/music.mp3’;
  3.  
  4. // open file
  5. if ($fp_remote = fopen($remote_file, ‘rb’)) {
  6.  
  7.     // local filename
  8.     $local_file = ‘/tmp/music.mp3’;
  9.  
  10.      // read buffer
  11.     if ($fp_local = fopen($local_file, ‘wb’)) {
  12.         while ($buffer = fread($fp_remote, 8192)) {
  13.  
  14.             // write buffer in file
  15.             fwrite($fp_local, $buffer);
  16.         }
  17.  
  18.         // close local
  19.         fclose($fp_local);
  20.        
  21.     }
  22.     // close remote
  23.     fclose($fp_remote);
  24. }
[pb_builder]

Check Also

How to list files in a directory in PHP?

<?php if ($handle = opendir(‘/path/to/directory’)) {     echo "Directory handle: $handlen";     echo …

Advertisment ad adsense adlogger