Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

security - Can I serve MP3 files with PHP?

In the same way that it's possible to serve up images with php, for use in CAPTACHAS and such, is it possible to do the same with audio files?

I've tried this

<?php

$track = "sometrack.mp3";

if(file_exists($track)) {
    header('Content-type: audio/mpeg');
    header('Content-length: ' . filesize($track));
    header('Content-Disposition: filename="sometrack.mp3"');
    header('X-Pad: avoid browser bug');
    header('Cache-Control: no-cache');
    print file_get_contents($track);
} else {
    echo "no file";
}

I'm using Safari, which can play MP3 files. It's kicking Safari into the right mode, I get the Quicktime controls for a few seconds, and then "No Video".

I'm trying to protect files from unauthorized download in case you're wondering why I'd want to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your Content-Disposition should be:

header('Content-Disposition: attachment; filename="sometrack.mp3"');

Not sure if that's the problem though. I would also recommend using readfile to output the file:

readfile($rSong);

Also, it can't hurt to use an exhaustive Content-Type header, and set the Content-Transfer-Encoding:

header("Content-Transfer-Encoding: binary"); 
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3"); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...