• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP Uploaded File not arriving to server folder

chrisj

Coder
I am still testing a web page where a video is recorded/captured and autoplayed successfully, however, upon Upload the file does not arrive to the server folder.
Here's the php:

PHP:
<?php
foreach (array('video', 'audio') as $type) {
    if (isset($_FILES["${type}-blob"])) {

        $fileName = $_POST["${type}-filename"];

       $uploadDirectory = 'uploads/' . $fileName;

            // make sure that one can upload only allowed audio/video files
            $allowed = array(
                'webm',
                'wav',
                'mp4',
                'mov'
    );

    $extension = pathinfo($uploadDirectory, PATHINFO_EXTENSION);
    if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
        echo 'Invalid file extension: '.$extension;
        return;
    }


$new_filepath = "uploads/" . uniqid() . ".". $extension;

if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $new_filepath)) {

         echo (" problem moving uploaded file");
       }

    }
}
?>

I read about adding this:
PHP:
file_put_contents('log.txt',print_r($_FILES,true),FILE_APPEND);

But, I don't know how/where to add that. Maybe another suggestion?
Any guidance to help me determine why the uploaded file does not arrive, is appreciated
 

Mutiny

Active Coder
Was this working the last time we looked at it, or was it never working?

What are the file permissions on the folder where the files are to be uploaded? It needs to be writable, so it should have permissions likely of either 644 or 755. If you look at it in a file manager, for instance CPanel's file manager, you should be able to see what the write permissions are on the directory.
 

chrisj

Coder
Thanks again for your reply.
After Upload is selected, and some time passes, the page displays a pop-up dialog box showing "Ok" (via chrome -desktop), I am assuming that is when the file finally arrives in the uploads/ folder. And via iPhone-Safari, (after much longer time) dialog box displays showing "Close". Sometimes the file does not arrive in the uploads/ folder via iPhone. After much testing I'm beginning to think the page needs to be hard refreshed (to have a successful upload) upon the the dialog box appearing - might solve the iPhone issue. Can you suggest a proper code for that? Not to clear all cache, just the page. Also, where can I change the dialog box to something more informative, like "File has been sent"?
Much thanks again I look forward to any additional help.
 

Mutiny

Active Coder
So, to be clear the file is uploading successfully in Chrome and you get the "Ok" dialog. On the iPhone you get a different dialog that says "Close". On iPhone files are not always uploaded, but in Chrome they are?

This sounds like a device specific problem (iOS only) and it seems the problem is more likely to be a Javascript issue than an issue with your PHP file. What's the latest version of the Javascript code you are using?
 

chrisj

Coder
Thanks again. Regarding "latest version of the Javascript code you are using", on the web page? Or on the mobile device? I'm not sure what you are asking. If you're saying do I have something like this on my web page: <script src='../javascript/script.js'></script> the answer is no, just the code on the page:

JavaScript:
let blobs = [];
let stream, mediaRecorder, blob;

async function startRecording() {
  stream = await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true,
  });
  mediaRecorder = new MediaRecorder(stream);
  mediaRecorder.ondataavailable = (event) => {
    // Let's append blobs for now, we could also upload them to the network.
    if (event.data) {
      blobs.push(event.data);
    }
  };
  mediaRecorder.onstop = doPreview;
  // Let's receive 1 second blobs
  mediaRecorder.start(1000);
}

function endRecording() {
  // Let's stop capture and recording
  mediaRecorder.stop();
  stream.getTracks().forEach((track) => track.stop());
}

function doPreview() {
  if (!blobs.length) {
    return;
  }
  // Let's concatenate blobs to preview the recorded content
  blob = new Blob(blobs, { type: mediaRecorder.mimeType });
  video.src = URL.createObjectURL(
    blob,
  );
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function uploadFile() {
            // create FormData
          var fileType = 'video'; // or "audio"
         var fileName = 'vid-.webm';
           var formData = new FormData();
           var request = new XMLHttpRequest;
          formData.append(fileType + '-filename', fileName);
          formData.append(fileType + '-blob', blob);
         request.open("POST", "/save1.php");

         request.onreadystatechange = function() {
         if(request.readyState==4) {
         alert(request.responseText);
         }
        }

            request.send(formData);
       }
 

Ghost

Active Coder
I wrote a function a while back that can check files for errors in the PHP uploading process... Maybe it will help you. You won't be able to copy and paste this and expect it to work for you because there is custom error reporting here. You can use the numbers 1-8 if the $_FILES['yourfile']['error'] != 0
check file for errors with php:
public function check_for_errors($file){
            if(isset($file['error']) && $file['error'] != 0){
                $file_errors = array(
                    1=>"The uploaded file exceeds the maximum file size allowed by our server.", // max file size from php ini directive
                    2=>"The uploaded file exceeds the maximum file size allowed by this feature.", // max file size from html form
                    3=>"The uploaded file was only partially uploaded.",
                    4=>"No file was uploaded.",
                    6=>"We cannot upload your file at this time.", // Missing a temporary folder to save file to
                    7=>"We cannot save your file at this time.", // Failed to write file to disk
                    8=>"Your file cannot be uploaded right now. Please try again later." // 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
                );
                if(isset($file_errors[$file['error']])){
                    $this->submitError($file_errors[$file['error']]);
                } else {
                    $this->submitError("There is a problem with the file you are uploading. We cannot save this file at this time.");
                }
                return false;
            } else if(!isset($file['size']) || $file['size'] == 0){
                $this->submitError("The file you are uploading has no file size and does not appear to be valid.");
                return false;
            } else {
                return true;
            }
        }

Usage is very simple:
Code:
$errors = check_for_errors($_FILES['upload']);
if($errors == false){
    // no errors with file upload
}
 
Last edited:

Top