I've searched through the forums for something similar to what I'm trying to do, found several results, but none of which seemed to work. I have a script, download.php in the root of a folder that houses multiple audio files. The script is accessed by a link on an artist's profile that passes the id of their song in the database. download.php takes the id, runs a MySQL query to obtain the path to the song, and then passes that information to a set of header() calls in an effort to force download the file. The problem lies when the script attempts to download the file. Instead of downloading the requested file, it tries to download the script itself. Any help is greatly appreciated!

<?php

$id = $_GET['aid'];

$query = "SELECT title, path FROM audio WHERE id = '".$id."'";
$result = mysql_query($query);
$audio = mysql_fetch_assoc($result);
$path = $audio['path'];
$file = substr($path, 7);

$fp = fopen($path,'rb');

header("Content-Disposition: attachment; filename=".$file."");
header("Content-Type: audio/x-mp3");
header("Content-Length: " . filesize($path));
fpassthru($path); 


?>

The $file variable is simply the file with the directory information stripped away from the beginning since the download.php script is, in essence, in the same directory as all the audio files.

I.E. If $path = /directory/artist-song.mp3 then $file = artist-song.mp3

    I'd start by putting more error-checking in to see if we can narrow down where the problem is:

    $id = (isset($_GET['aid'])) ? trim($_GET['aid']) : '';
    if($id === "")
    {
       die("No ID received");
    }
    
    $query = "SELECT title, path FROM audio WHERE id = '".$id."'";
    $result = mysql_query($query) or die("Query failed: $query - ".mysql_error());
    if(mysql_num_rows($audio))
    {
       $audio = mysql_fetch_assoc($result);
       $path = $audio['path'];
       $file = basename($path);  // simpler way to get the filename
       if(file_exists($path))
       {
          if(is_readable($path))
          {
             header("Content-Disposition: attachment; filename=".$file."");
             header("Content-Type: audio/x-mp3");
             header("Content-Length: " . filesize($path));
             readfile($path);  // you can just use this instead of fopen/fpassthru
          }
          else
          {
             die("File $path is not readable");
          }
       }
       else
       {
          die("File $path does not exist");
       }
    }  
    else { die("No match found for ID $id"); }

      Thanks for the help! I got it working after tinkering around with the code you posted. Made things much much simpler! Appreciate the expertise.

        Write a Reply...