AmyllaVimiar
AmyllaVimiar

Reputation: 297

unknown file name when downloading from server in PHP

I'm trying to download a file from my server using PHP by using a button.

file is downloading is working properly. However whenever I try downloading a file, the file name changed with unknown file format of ".pn1, .pn5, etc" instead of PNG.

Here's the button to download the file

<a href="download.php"></a>

and Here's my download PHP.

$value = custom_query("SELECT * FROM tbl_training ORDER BY id DESC LIMIT 

1");
if($value->rowCount()>0) {
    while ($r = $value->fetch(PDO::FETCH_ASSOC)) {
        $test_id = substr($r['test_id'], -1);
        $new_id = $test_id + 1;
        $new_file_name = substr($r['test_id'], 0, -1) . "" . $new_id;

    }
}
header ("Content-Disposition: attachment; filename='$new_file_name.png'");
header("Content-Length: " . filesize("1234-56689.png"));
header("Content-Type: application/octet-stream;");
readfile("1234-56689.png");
echo $ab = AB(50);
$abtf= ABTF(50);
$tf = TF(50);
$ab_result = substr($ab, 0, -1);
$abtf_result = substr($abtf, 0, -1);
$tf_result = substr($tf, 0, -1);

        $data1 = array(
                "test_id"=>$new_file_name,
                "stud_id"=>$new_file_name,
                "section"=>"Section A",
                "a_key"=>$ab_result
        );
        $data2 = array(
            "test_id"=>$new_file_name,
            "stud_id"=>$new_file_name,
            "section"=>"Section A",
            "a_key"=>$abtf_result
        );
        $data3 = array(
            "test_id"=>$new_file_name,
            "stud_id"=>$new_file_name,
            "section"=>"Section A",
            "a_key"=>$tf_result
        );
        db_insert('tbl_training', $data1);
        db_insert('tbl_training_abtf', $data2);
        db_insert('tbl_training_tf', $data3);

Everything works fine aside from the filename changed to this one enter image description here

Thank you for helping me! :)

Upvotes: 0

Views: 823

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

When you use...

$new_file_name = substr($r['test_id'], 0, -1) . "" . $new_id;

you are just taking the last character off the string and adding the ID on. If this string contained "1234.png", you would end up with something like "1234.pn1". So it would be worth checking your database to see what these file names actually contain.

This instead ensures that it removes the extension by taking the string before the "." and then the .png extension is added back in your header output...

$new_file_name = strstr($r['test_id'], ".", true) . $new_id;

Upvotes: 1

Related Questions