Sending mp3 file through PHP to be used with the audio tag of HTML5 fails in the middle of the mp3

南笙酒味 提交于 2019-12-06 08:24:39
Brice

I know this is an old post but I was able to get this working with two files and index.php and example.php.

this is example.php that's checking a databse for a hash and a used field to know if the file has been used before

<?php

  if(isset($_GET['hash'])){
    $mysqli = new mysqli('host_here','user_here','password_here','database_here');
    $result = $mysqli->query("select * from hashes where hash = '{$_GET['hash']}'  limit 1");

    $row = $result->fetch_array();
  }

  if(isset($row['used']) && $row['used'] == 0){
    $mysqli->query("update hashes set used=1 where hash = '{$_GET['hash']}'");
    $filename = "example.mp3";
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: audio/mpeg");
    header('Content-length: ' . filesize($filename)); 
    //If this is a secret filename then don't include it.
    header('Content-Disposition: inline');
    //Otherwise you can add it like so, in order to give the download a filename
    //header('Content-Disposition: inline;filename='.$filename);
    header('Cache-Control: no-cache');


    readfile($filename);
    exit;
  }

  elseif(isset($row['used']) && $row['used'] == 1){
    die("you can't just download this dude");
  }

and here is index.php with the audio tag that will allow playing but not downloading of the mp3.

<html>
<body>
<?php

  $mysqli = new mysqli('localhost','root','','test_mp3');
  $rand = mt_rand();
  $hash = md5($rand);
  $result = $mysqli->query("insert into hashes (hash,used) values('$hash',0)");

?>
  <audio controls>
    <source src="example.php?hash=<?=$hash?>" type="audio/mpeg">
  </audio>
</body>
</html>

there is a database table with just a hash and a used field for this example to work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!