0

Why my PHP code returns nothing while uploading file greater than 30MB approx, but it works on localhost the problem is in Server Side. Sometime it says 503 error or err: NET CONNECTION RESET. but mostly returns nothing.

when i upload file that are less than 25MB they get uploaded pretty quietly.

And also if someone can help me with the progress bar while data is been uploading in drive , in my code the progress is showing but after the file is been uploaded, not while uploading(I read about the getURI and ... but didn't understood properly) can anyone guide me here too?

I am using V3 of Google-drive-api.

INDEX.php

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">

    <title>Google Drive Example App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                $('.myprogress').css('width', '0');
                $('.msg').text('');
                var filename = $('#filename').val();
                var myfile = $('#myfile').val();
                var discription = $('#discription').val();
                if (filename == '' || myfile == '') {
                    alert('Please enter file name and select file');
                    return;
                }
                var formData = new FormData();
                formData.append('pdf', $('#myfile')[0].files[0]);
                formData.append('name', filename);
                formData.append('discription', discription);
                $('#btn').attr('disabled', 'disabled');
                 $('.msg').text('Uploading in progress...');
                $.ajax({
                    url: 'action.php',
                    data: formData,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    // this part is progress bar
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.myprogress').text(percentComplete + '%');
                                $('.myprogress').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function (data) {
                        $('.msg').text(data);
                        $('#btn').removeAttr('disabled');
                    }
                });
            });
        });


    </script>
 </head>
 <body>
      <div class="container">
            <div class="row">
                <h3>File Upload</h3>
                <form id="myform" method="post">
                    <div class="form-group">
                        <label>File name: </label>
                        <input class="form-control" type="text" id="filename" /> 
                    </div>
                    <div class="form-group">
                        <label>File Discription: </label>
                        <input class="form-control" type="text" id="discription" /> 
                    </div>
                    <div class="form-group">
                        <label>Select file: </label>
                        <input class="form-control" type="file" id="myfile" />
                    </div>
                    <div class="form-group">
                        <div class="progress">
                            <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                        </div>
                        <div class="msg"></div>
                    </div>
                    <input type="button" id="btn" class="btn-success" value="Upload" />
                </form>
            </div>
        </div>
    </body>

</html>

ACTION.php

<?php

   ini_set('upload_max_filesize', '1000M');
   ini_set('post_max_size', '1000M');
   set_time_limit(5000);

if(isset($_FILES['pdf']) && isset($_POST['name'])){
    $name = $_POST['name'];
    if($name == ''){
        echo "file name is Empty";
    }else{
        $discription = $_POST['discription'];
        $target_dir = "files/";
        $file_name = basename($_FILES["pdf"]["name"]);
        $filesize = $_FILES['pdf']['size'];
        $FileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
        $file = "test_file.".$FileType;
        $file_path = $target_dir . $file;
        $tmpname = $_FILES['pdf']['tmp_name'];
        $upload = move_uploaded_file($tmpname, $file_path);

        if($upload == true){
            include_once __DIR__ . '/google-api-php-client-master/vendor/autoload.php';
            $client = new Google_Client();
            $client->setAuthConfig('credentials.json');
            $client->addScope('https://www.googleapis.com/auth/drive.file');

            $service = new Google_Service_Drive($client);
            $service = new Google_Service_Drive($client);
            $client->getAccessToken();

            $file = new Google_Service_Drive_DriveFile();
            $chunkSizeBytes = 1 * 1024 * 1024;
            $client->setDefer(true);

            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            $parentId = "PARENT_FOLDER_ID";
            $file->setParents(array($parentId));

            $mime_type = finfo_file($finfo, $file_path);
            $file->setName($name);
            $file->setDescription($discription);

            $response = $service->files->create($file);                

            // Create a media file upload to represent our upload process.
            $media = new Google_Http_MediaFileUpload(
              $client,
              $response,
              $mime_type,
              null,
              true,
              $chunkSizeBytes
            );
            $media->setFileSize(filesize($file_path));

            function readVideoChunk ($handle, $chunkSize){
                $byteCount = 0;
                $giantChunk = "";
                while (!feof($handle)) {
                    $chunk = fread($handle, $chunkSize);
                    $byteCount += strlen($chunk);
                    $giantChunk .= $chunk;
                    if ($byteCount >= $chunkSize)
                    {
                        return $giantChunk;
                    }
                }
                return $giantChunk;
            }

            // Upload the various chunks. $status will be false until the process is complete.
            $status = false;
            $handle = fopen($file_path, "rb");
            while (!$status && !feof($handle)) {
                // An example of a read buffered file is when reading from a URL
                $chunk = readVideoChunk($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
               //if want to show the progress bar too but not working while uploading , but it shows the uploaded chunks after the files is been uploaded. 
                if(!$status){ //nextChunk() returns 'false' whenever the upload is still in progress
                    echo 'sucessfully uploaded file up to byte ' . $media->getProgress() . ' which is ' . ( $media->getProgress() / $chunkSizeBytes ) . '% of the whole file';
                }
            }
            $result = false;
            if ($status != false) {
                $result = $status;
            }

            $file_id = $status['id'];

            fclose($handle);

            // Reset to the client to execute requests immediately in the future.
            $client->setDefer(false);
           //i am manually creating the wbViewLink by the ID i am getting in response 
            $webViewLink = "https://drive.google.com/file/d/$file_id/view?usp=drivesdk";

            $myobj = new StdClass();
            $myobj->{'alt_link'} = $webViewLink;
            $myobj->{'size'} = $filesize;
            print_r($myobj);
        }else{
            echo "upload failed";
        }
    }
  }
?>

Can anyone Help me here ? I am using service account as you can see to Authenticate the user on my behalf...

when everything is fine then result is something like this{image}

but when i upload file then is greater then 30MB result (only on server, on localhost is works fine) {image}

also you can see in the 2nd image the status in OK but still no response.

  • Have you tried increasing the ```set_time_limit(5000);``` just in case the upload takes longer than that when doing it to the server (it makes sense in localhost to be quick)? Also, could you confirm me if I got this right? : *"You successfully uploaded when not using the server and also using the server you successfully uploaded a 25MB file."* – Mateo Randwolf Jun 02 '20 at 07:39
  • 1
    yup i increased it and it also allowed me to upload max 80-90 MB of file..but again when i tried to upload MB file it just not returned nothing @MateoRandwolf – Pradeep Prasad Jun 03 '20 at 09:15
  • Then I don't think the issue is with the file size but rather with the file itself and how you are sending it. Does your file get eventually updated or not at all? Also, why are you not including your file metadata type here ```$service->files->create($file);``` and you are just using the file? You need to specify this as well when uploading a file. [This answer can be useful on how to implement this](https://stackoverflow.com/a/25715084/12835757). Note that in the answer ```$file``` is the metadata and ```$data``` is the actual image. – Mateo Randwolf Jun 04 '20 at 08:22
  • [Check the documentation](https://developers.google.com/drive/api/v3/manage-uploads) for more about upload types and how to upload a file and let me know if this solves the issue :D – Mateo Randwolf Jun 04 '20 at 08:23
  • @MateoRandwolf i have gone through the documentation several times and also many people have even said that documentation is not updated properly from v2 to v3 so many classes are updated but their updation is not mentioned in documentation.... – Pradeep Prasad Jun 04 '20 at 11:12
  • 1
    Have you tried implementing what I have suggested related to the way you create the files (using the proper metadata and file content)? – Mateo Randwolf Jun 05 '20 at 07:31
  • yes i have given proper meta data in uplodation && if there was any mistake in api code then there must be an error while uploading right? – Pradeep Prasad Jun 06 '20 at 14:07
  • Hi ! So basically the API is not returning any error because you are performing a [simple media upload](https://developers.google.com/drive/api/v3/manage-uploads#simple). However, as stated in the multipart and simple media upload documentation of the API, for larger files or those which metadata is important, you must use the [multipart upload](https://developers.google.com/drive/api/v3/manage-uploads#multipart). This upload type request you to send the data and metadata of the file separately as two independent parameters of the function. Please, try doing so and let me know how it goes :D – Mateo Randwolf Jun 08 '20 at 07:22

1 Answers1

1

You can't always override upload size setting with ini_set, depending on hosting provider. Try this in your .htaccess:

php_value upload_max_filesize 100M
php_value post_max_size 100M
Sam
  • 81
  • 3