Search code examples
phpheaderblockhtml

play mp3 with php header function is blocking page


My test server is apache 2 to work php coding. i want to create a mp3 server.

Everything is working fine, however today i tried to build an admin page by taking the mp3 info, change it, delete etc. There is a play button in page for selected mp3, when clicked to play button, file loading with header option and playing,

Sample code is here:

session control &
$filename = '/home/bla..bla/mp3/'. $_GET['v'] . '.mp3';
if(file_exists($filename)) {
    header('Content-Type: audio/mpeg');
    header('Content-length: '.filesize($filename));
    header('X-Pad: avoid browser bug');
    header('Cache-Control: no-cache');
    readfile($filename);
}else{
    exit();
}

Everything looks fine, but when i click to another button (e.g. search again mp3 with ajax code or take value with javascript in same page) nothing is happening.

Page is waiting to load mp3 file. looks like blocking request. when mp3 loading %60 or %70, query is coming.

if i can't find a solution,i will be killer :)

ps: my system build on apache2, PHP5 , MySQL, using audio tag in admin page but same problem with jplayer.


Solution

  • Most likely you're running into session locking. When requesting a page in which you session_start(), the session file is opened and locked to prevent problems with concurrent access. The file stays locked until the current script is finished. While the file is locked, other processes can't access it and will wait until it becomes unlocked.

    Before you do any long-running tasks like streaming an MP3 file, unlock the session with session_write_close.

    Even better, let the web server handle the mundane task of streaming a file, don't keep a PHP process busy with it. Try mod_xsendfile.