1

I have written some code using streams that sends a file via a multiform post to another website. So this is php server code to -> another web server. I currently cannot use "curl", I constrained to streams.

My concern (Comment below, Concern here,) is if I encounter a very large file it may exhaust the memory on the php web server.

Is there a way of working with PHP streams to write directly to request stream when using php stream that point to a url (rest api endpoint)? right now after everything is put together, it issues a

file_get_contents(...)

So here is a snippet of code that is creating and sending a the file.

    private function getOptionsForMulitPartFile($request, $cred, $file)
    {

        $mimeType = $this->getMimeType($file);
        $contentType = 'Content-Type: multipart/form-data; boundary=' . MULTIPART_BOUNDARY;
        $contentLength = "Content-Length: " . filesize($file->getFilePathAndName());

        $file_contents = $file->readWholeFile(); //<----Concern here, that file maybe too large.

        $data =  "--" . MULTIPART_BOUNDARY . "\r\n" .
            "Content-Disposition: form-data; name=\"".FORM_FIELD."\"; filename=\"" . basename($file->getFilePathAndName()) . "\"\r\n" .
            "Content-Type: " . $mimeType . "\r\n\r\n" . $file_contents."\r\n";

        $data  .=  "--". MULTIPART_BOUNDARY . "--\r\n";

        // set up the request context

        return $this->createOption($request, $cred, $data, $contentType, $contentLength);
    }
MacWise
  • 520
  • 3
  • 13
  • Instead of building the multipart request body, you can just generate it on the fly and write it to the stream. Instead of then calling readwholefile, read it in pieces and write to the stream as you go, then you won't exhaust memory. – drew010 May 20 '16 at 21:21
  • 1
    file_get_contents doesn't really give you a writable request stream. it's readonly – MacWise May 23 '16 at 15:47
  • Can you provide a simple example? – MacWise May 24 '16 at 11:58

1 Answers1

0

While reading large files you can use ob_flush() + stream_copy_to_stream methods so every X byte you read from file you can transfer to another server.

Alex.Default
  • 236
  • 3
  • 16