2017-08-10 18:32
浏览 87


I'm working on an online experiment (using the jsPsych library) where participants (each with a code number randomly assigned by the script) will record a number of .wav files. I then want to upload to the server with names that include the participant's code number and the item number associated with that recording. Each participant will be creating something like 36 different short .wav files.

It looks like recorderjs and recordermp3.js are what I need to record the audio on the browser side (see RecorderJS uploading recorded blob via AJAX), but I'm having difficulty finding the information I need to create a PHP script that will save a file of unknown file name.

Here's the relevant javascript:

function stopRecording(subjectID, item_number) {
    recorder && recorder.stop();
    console.log('Stopped recording.');
    recorder && recorder.exportWAV(function(blob) {
        var xhr=new XMLHttpRequest();
        xhr.onload=function(e) {
            if(this.readyState === 4) {
                console.log("Server returned: ",;
        var fd=new FormData();
        fd.append(subjectID + item_number + ".wav", blob);"POST","upload_wav.php",true);

And here's what I have so far for PHP:

    $target_dir = 'audio/';
    $target_file=$target_dir . basename[$_FILES["fileToUpload"]["name"];
    move_uploaded_file($_FILES[“fileToUpload”][“tmp_name”], $target_file);

My question is very similar to Saving WAV File Recorded in Chrome to Server and HTML5 & getUserMedia - Record Audio & Save to Web Server after Certain Time but different in that I don't know what the filename of the uploaded file will be and I want to use PHP (mostly because I was told to). What can I use instead of "fileToUpload" in the php script to get this script to work for any .wav file that is sent to it?

In case you haven't already guessed I have learned everything in know about javascript and PHP in the last month or so, so please be gentle with the n00b. I have looked in various PHP tutorials and documentations but just don't seem to be finding what I'm looking for there. Code would be most appreciated.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzuoyue6556 2017-08-10 21:56

    First of all, you should add some checks to make sure you won't get post flooded. The minimal way to do this would be by making sure the POST comes from the same server IP (though there are several ways to spoof that):


    Also, make sure you only execute this script when you actually receive a file>

    if (!$_FILES) {
        die('File missing');

    As for your filename problem: You are only uploading one file at a time, so $_FILES will only have one element that you can retrieve with current().

    $target_dir = 'audio/';
    $file = current($_FILES);
    $target_file = $target_dir . basename($file['name']);
    move_uploaded_file($file['tmp_name'], $target_file);
    // why would you do this?
    点赞 评论

相关推荐 更多相似问题