Downloading a file with different name

Discussion in 'PHP' started by shoeshine, Dec 26, 2007.

  1. #1
    Hi all,

    I have this problem. I want to build a script that takes a number as parameter. When accessing the script, I want the script to start download a file that is on the server. The file is called xyz.mp3. But if the script is accessed:

    script.php?number=1

    it will start downloading xyz.mp3 but rename it to 1.mp3

    Any functions that might help me.Thank you
     
    shoeshine, Dec 26, 2007 IP
  2. hogan_h

    hogan_h Peon

    Messages:
    199
    Likes Received:
    30
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can pass the script name to the header function.
    
    $file_name = "whatever.mp3";
    header('Content-Disposition: attachment; filename=' . $file_name);
    
    PHP:
     
    hogan_h, Dec 26, 2007 IP
  3. shoeshine

    shoeshine Peon

    Messages:
    250
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    hey hogan_h
    Thank for your response...
    But the problem is that 1.mp3 does not exists. That is I first want to to rename xyz.mp3 to 1.mp3 and make the script download it. On the other hand i dont want to physically rename.
     
    shoeshine, Dec 26, 2007 IP
  4. shoeshine

    shoeshine Peon

    Messages:
    250
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    hogan_h I managed to get it working :) Thank for your fast help. Rep added.
     
    shoeshine, Dec 26, 2007 IP
    hogan_h likes this.
  5. hogan_h

    hogan_h Peon

    Messages:
    199
    Likes Received:
    30
    Best Answers:
    0
    Trophy Points:
    0
    #5
    1.mp3 doesn't need to exist.

    You simply send the header with the file_name of your choice and then read and output the actual file.
    Example code:
    
    $real_file = "xyz.mp3"; // if this file is inside a folder, you need complete path here
    $download_file_name = "1.mp3";
    header('Content-Description: File Transfer');
    header("Content-Length: ".filesize($real_file));
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . $download_file_name); // Download prompt will contain this file name
    readfile($real_file); // this will read and output physical file
    
    PHP:
    Edit: Just saw you already got it working :)
     
    hogan_h, Dec 26, 2007 IP
  6. shoeshine

    shoeshine Peon

    Messages:
    250
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Yep I found the same example that you gave me on php.net ;) Thank you very much hogan_h ;)
     
    shoeshine, Dec 26, 2007 IP