Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How does Muaz's server handle PHP? #727

Open
rayj00 opened this issue Feb 12, 2021 · 15 comments
Open

How does Muaz's server handle PHP? #727

rayj00 opened this issue Feb 12, 2021 · 15 comments

Comments

@rayj00
Copy link

rayj00 commented Feb 12, 2021

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

@zahidgani
Copy link

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

index.php

<script src="https://www.webrtc-experiment.com/RecordRTC.js"></script> <style> video { max-width: 100%; border: 5px solid yellow; border-radius: 9px; } body { background: black; } h1 { color: yellow; } </style>
<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();**

@rayj00
Copy link
Author

rayj00 commented Feb 19, 2021

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
Copy link
Author

rayj00 commented Feb 23, 2021

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?

@zahidgani
Copy link

zahidgani commented Feb 25, 2021 via email

@rayj00
Copy link
Author

rayj00 commented Feb 25, 2021

Where is fileDownloadURL initialized?

@zahidgani
Copy link

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
Copy link

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

@rayj00
Copy link
Author

rayj00 commented Feb 25, 2021

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

@zahidgani
Copy link

zahidgani commented Feb 25, 2021 via email

@rayj00
Copy link
Author

rayj00 commented Feb 25, 2021

See my comment above from Feb 23.

@rayj00
Copy link
Author

rayj00 commented Mar 5, 2021

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

@rayj00
Copy link
Author

rayj00 commented Mar 6, 2021

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

@zahidgani
Copy link

zahidgani commented Mar 8, 2021 via email

@jimztercrack
Copy link

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

@rayj00
Copy link
Author

rayj00 commented Jul 6, 2021

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants