RecordRTC icon indicating copy to clipboard operation
RecordRTC copied to clipboard

How does Muaz's server handle PHP?

Open rayj00 opened this issue 3 years ago • 15 comments

I am trying to upload a blob(webm) file to the server but no matter what I use from Muaz's code examples, it won't work.

I am confused on how the server is supposed to accept PHP?

If you are using PHP with Muaz's server code please let me know how you do it.

Thanks,

Ray

rayj00 avatar Feb 12 '21 17:02 rayj00

Hi Here is the full code working fine for me to record video and upload it to your folder

index.php

<body>
    <h1 id="header">RecordRTC Upload to PHP</h1>
    <video id="your-video-id" controls autoplay playsinline></video>

    <script type="text/javascript">
        // capture camera and/or microphone
        navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function(camera) {

            // preview camera during recording
            document.getElementById('your-video-id').muted = true;
            document.getElementById('your-video-id').srcObject = camera;

            // recording configuration/hints/parameters
            var recordingHints = {
                type: 'video'
            };

            // initiating the recorder
            var recorder = RecordRTC(camera, recordingHints);

            // starting recording here
            recorder.startRecording();

            // auto stop recording after 5 seconds
            var milliSeconds = 5 * 1000;
            setTimeout(function() {

                // stop recording
                recorder.stopRecording(function() {
                    
                    // get recorded blob
                    var blob = recorder.getBlob();

                    // generating a random file name
                    var fileName = getFileName('webm');

                    // we need to upload "File" --- not "Blob"
                    var fileObject = new File([blob], fileName, {
                        type: 'video/webm'
                    });

                    uploadToPHPServer(fileObject, function(response, fileDownloadURL) {
                        if(response !== 'ended') {
                            document.getElementById('header').innerHTML = response; // upload progress
                            return;
                        }

                        document.getElementById('header').innerHTML = '<a href="' + fileDownloadURL + '" target="_blank">' + fileDownloadURL + '</a>';

                        alert('Successfully uploaded recorded blob.');

                        // preview uploaded file
                        document.getElementById('your-video-id').srcObject = null;
                        document.getElementById('your-video-id').src = fileDownloadURL;

                        // open uploaded file in a new tab
                        window.open(fileDownloadURL);
                    });

                    // release camera
                    document.getElementById('your-video-id').srcObject = document.getElementById('your-video-id').src = null;
                    camera.getTracks().forEach(function(track) {
                        track.stop();
                    });

                });

            }, milliSeconds);
        });

        function uploadToPHPServer(blob, callback) {
            // create FormData
            var formData = new FormData();
            formData.append('video-filename', blob.name);
            formData.append('video-blob', blob);
            callback('Uploading recorded-file to server.');

            var upload_url = 'save.php';
            // var upload_url = 'RecordRTC-to-PHP/save.php';

            var upload_directory = upload_url;
            // var upload_directory = 'RecordRTC-to-PHP/uploads/';
            
            makeXMLHttpRequest(upload_url, formData, function(progress) {
                if (progress !== 'upload-ended') {
                    callback(progress);
                    return;
                }
                var initialURL = upload_directory + blob.name;
                callback('ended', initialURL);
            });
        }

        function makeXMLHttpRequest(url, data, callback) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    if (request.responseText === 'success') {
                        callback('upload-ended');
                        return;
                    }
                    alert(request.responseText);
                    return;
                }
            };
            request.upload.onloadstart = function() {
                callback('PHP upload started...');
            };
            request.upload.onprogress = function(event) {
                callback('PHP upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
            };
            request.upload.onload = function() {
                callback('progress-about-to-end');
            };
            request.upload.onload = function() {
                callback('PHP upload ended. Getting file URL.');
            };
            request.upload.onerror = function(error) {
                callback('PHP upload failed.');
            };
            request.upload.onabort = function(error) {
                callback('PHP upload aborted.');
            };
            request.open('POST', url);
            request.send(data);
        }

        // this function is used to generate random file name
        function getFileName(fileExtension) {
            var d = new Date();
            var year = d.getUTCFullYear();
            var month = d.getUTCMonth();
            var date = d.getUTCDate();
            return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
        }

        function getRandomString() {
            if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                var a = window.crypto.getRandomValues(new Uint32Array(3)),
                    token = '';
                for (var i = 0, l = a.length; i < l; i++) {
                    token += a[i].toString(36);
                }
                return token;
            } else {
                return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
            }
        }
    </script>

    
    <footer style="margin-top: 20px;"><small id="send-message"></small></footer>
    <script src="https://www.webrtc-experiment.com/common.js"></script>

</body>

save.php

**header("Access-Control-Allow-Origin: *"); error_reporting(E_ALL); ini_set('display_errors', 1);

set_error_handler("someFunction");

function someFunction($errno, $errstr) { echo '

Upload failed.


'; echo '

'.$errstr.'

'; }

function selfInvoker() { if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) { echo 'Empty file name.'; return; }

  // do NOT allow empty file names
  if (empty($_POST['audio-filename']) && empty($_POST['video-filename'])) {
      echo 'Empty file name.';
      return;
  }

  // do NOT allow third party audio uploads
  if (false && isset($_POST['audio-filename']) && strrpos($_POST['audio-filename'], "RecordRTC-") !== 0) {
      echo 'File name must start with "RecordRTC-"';
      return;
  }

  // do NOT allow third party video uploads
  if (false && isset($_POST['video-filename']) && strrpos($_POST['video-filename'], "RecordRTC-") !== 0) {
      echo 'File name must start with "RecordRTC-"';
      return;
  }
  
  $fileName = '';
  $tempName = '';
  $file_idx = '';
  
  if (!empty($_FILES['audio-blob'])) {
      $file_idx = 'audio-blob';
      $fileName = $_POST['audio-filename'];
      $tempName = $_FILES[$file_idx]['tmp_name'];
  } else {
      $file_idx = 'video-blob';
      $fileName = $_POST['video-filename'];
      $tempName = $_FILES[$file_idx]['tmp_name'];
  }
  
  if (empty($fileName) || empty($tempName)) {
      if(empty($tempName)) {
          echo 'Invalid temp_name: '.$tempName;
          return;
      }

      echo 'Invalid file name: '.$fileName;
      return;
  }

  /*
  $upload_max_filesize = return_bytes(ini_get('upload_max_filesize'));
  if ($_FILES[$file_idx]['size'] > $upload_max_filesize) {
     echo 'upload_max_filesize exceeded.';
     return;
  }
  $post_max_size = return_bytes(ini_get('post_max_size'));
  if ($_FILES[$file_idx]['size'] > $post_max_size) {
     echo 'post_max_size exceeded.';
     return;
  }
  */

  $filePath = 'uploads/' . $fileName;
  
  // make sure that one can upload only allowed audio/video files
  $allowed = array(
      'webm',
      'wav',
      'mp4',
      'mkv',
      'mp3',
      'ogg'
  );
  $extension = pathinfo($filePath, PATHINFO_EXTENSION);
  if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
      echo 'Invalid file extension: '.$extension;
      return;
  }
  
  
  if (!move_uploaded_file($tempName, $filePath)) {
      if(!empty($_FILES["file"]["error"])) {
          $listOfErrors = array(
              '1' => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
              '2' => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
              '3' => 'The uploaded file was only partially uploaded.',
              '4' => 'No file was uploaded.',
              '6' => 'Missing a temporary folder. Introduced in PHP 5.0.3.',
              '7' => 'Failed to write file to disk. Introduced in PHP 5.1.0.',
              '8' => 'A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.'
          );
          $error = $_FILES["file"]["error"];

          if(!empty($listOfErrors[$error])) {
              echo $listOfErrors[$error];
          }
          else {
              echo 'Not uploaded because of error #'.$_FILES["file"]["error"];
          }
      }
      else {
          echo 'Problem saving file: '.$tempName;
      }
      return;
  }
  
  echo 'success';

} selfInvoker();**

zahidgani avatar Feb 15 '21 13:02 zahidgani

Thanks Zahid. The problem is I am using RTCMulticonnections with Scalable Broadcasting. So RTCMulticonnections does the getUserMedia. I can create the blob (webm) using RecordRTC. I have a start recording button and stop recording. I just need to save the blob to server and then convert it to mp4 (which I will use ffmpeg.). I am not sure your code will work?

rayj00 avatar Feb 19 '21 19:02 rayj00

I am getting a little further in my issue. When I enter your uploadtoPHP, I am getting this in the console:

12:31:51.435 response - PHP upload Progress 66% bcast.streamingworld.us:329:13 12:31:51.486 response - PHP upload Progress 68% bcast.streamingworld.us:329:13 12:31:51.537 response - PHP upload Progress 66% bcast.streamingworld.us:329:13 12:31:51.589 response - PHP upload Progress 70% bcast.streamingworld.us:329:13 12:31:51.641 response - PHP upload Progress 66% bcast.streamingworld.us:329:13 12:31:51.752 response - PHP upload Progress 74% bcast.streamingworld.us:329:13 12:31:51.803 response - PHP upload Progress 68% bcast.streamingworld.us:329:13 12:31:51.854 response - PHP upload Progress 66% bcast.streamingworld.us:329:13 12:31:51.978 response - PHP upload Progress 74% bcast.streamingworld.us:329:13 12:31:52.111 response - PHP upload Progress 66% bcast.streamingworld.us:329:13 12:31:52.162 response - PHP upload Progress 70% bcast.streamingworld.us:329:13 12:31:52.192 response - PHP upload failed.

Any ideas why?

rayj00 avatar Feb 23 '21 17:02 rayj00

Here is the full code you can check and work it fine.

On Tue, Feb 23, 2021 at 11:26 PM rayj00 [email protected] wrote:

I am getting a little further in my issue. When I enter your uploadtoPHP, I am getting this in the console:

12:31:51.435 response - PHP upload Progress 66% bcast.streamingworld.us:329 :13 12:31:51.486 response - PHP upload Progress 68% bcast.streamingworld.us:329 :13 12:31:51.537 response - PHP upload Progress 66% bcast.streamingworld.us:329 :13 12:31:51.589 response - PHP upload Progress 70% bcast.streamingworld.us:329 :13 12:31:51.641 response - PHP upload Progress 66% bcast.streamingworld.us:329 :13 12:31:51.752 response - PHP upload Progress 74% bcast.streamingworld.us:329 :13 12:31:51.803 response - PHP upload Progress 68% bcast.streamingworld.us:329 :13 12:31:51.854 response - PHP upload Progress 66% bcast.streamingworld.us:329 :13 12:31:51.978 response - PHP upload Progress 74% bcast.streamingworld.us:329 :13 12:31:52.111 response - PHP upload Progress 66% bcast.streamingworld.us:329 :13 12:31:52.162 response - PHP upload Progress 70% bcast.streamingworld.us:329 :13 12:31:52.192 response - PHP upload failed.

Any ideas why?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/muaz-khan/RecordRTC/issues/727#issuecomment-784389077, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABQEYI2TS7BGK6D3NFKAY6LTAPT43ANCNFSM4XRCQHOA .

zahidgani avatar Feb 25 '21 20:02 zahidgani

Where is fileDownloadURL initialized?

rayj00 avatar Feb 25 '21 20:02 rayj00

Here is only the code we have applied Start Record Stop Record When you stop record Upload button will be on When you click on upload button it save video in your local computer folder and there will be you can sent download path

zahidgani avatar Feb 25 '21 20:02 zahidgani

You may download full code here: http://webdhamaal.com/recordrst.zip

zahidgani avatar Feb 25 '21 20:02 zahidgani

I already can save it locally. That is not what I need, I need to send it from client to server!

rayj00 avatar Feb 25 '21 20:02 rayj00

that the save code also work on server side i have already applied it on server side what is the actual issue you are facing?

On Fri, Feb 26, 2021 at 2:14 AM rayj00 [email protected] wrote:

I already can save it locally. That is not what I need, I need to send it from client to server!

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/muaz-khan/RecordRTC/issues/727#issuecomment-786190995, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABQEYI5PYKQHWFLFSLBDKWLTA2ZBPANCNFSM4XRCQHOA .

zahidgani avatar Feb 25 '21 20:02 zahidgani

See my comment above from Feb 23.

rayj00 avatar Feb 25 '21 20:02 rayj00

It's Apache2 that handles the PHP and not the node server!

rayj00 avatar Mar 05 '21 12:03 rayj00

I had to reload PHP. Everything working now!! Yahoo!!!

rayj00 avatar Mar 06 '21 13:03 rayj00

Glad to hear it!

On Sat, Mar 6, 2021 at 6:58 PM rayj00 [email protected] wrote:

I had to reload PHP. Everything working now!! Yahoo!!!

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/muaz-khan/RecordRTC/issues/727#issuecomment-791940377, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABQEYI5RMVG6ZCFSJKNR4STTCIUYHANCNFSM4XRCQHOA .

zahidgani avatar Mar 08 '21 11:03 zahidgani

Please, If you want to choose a particular camera, How I can do it?,

jimztercrack avatar Jul 06 '21 17:07 jimztercrack

Please, If you want to choose a particular camera, How I can do it?,

I am having the same issue....changing camera (front/back) for mobile broadcast. I really need this!

rayj00 avatar Jul 06 '21 17:07 rayj00