Question

I need to set php header("Content-Length: length"), where length is a byte value. Right now I have arbitrarily set it to 1 megabyte due to the variable size of my post request, but I want to dynamically generate this so that there isn't erroneous data.

How can I get the byte size of my object before I send it to the server. I am making a soapCall so I have to set the header before I do that call, instead of adding a parameter to curl or something.

Was it helpful?

Solution

You can do the following (there ought to be something better, I know):

$before = memory_get_usage(TRUE);
$objectClone = clone $yourObject;
$after = memory_get_usage(TRUE);
$objectSize = $after - $before;  #size of your object
$objectClone = $null; #dispose of clone

OTHER TIPS

I'm not familiar with SOAP, so forgive me if this doesn't apply to your situation.

I had to solve this problem not too long ago for a personal project of mine, where I dynamically generated and streamed large ZIPs to the user. My solution was to precompute the size of the object by generating it once and recording its size. The drawback to this solution is that the size needs to be recomputed if the contents of the object change, but if you have a finite number of objects whose sizes don't change often, it might work for you.

The code I used looks something like this:

ob_start();
$zip_length = 0;
$zip = new ZipStream();
foreach ($files as $virtual_path => $file_path) {
    $zip->add_file_from_path($virtual_path, $file_path);
    $zip_length += strlen(ob_get_contents());
    ob_clean(); /* prevent excessive memory usage */
}
$zip->finish();
$zip_length += strlen(ob_get_contents());
ob_end_clean();
/* Store $zip_length somewhere */

If this is too general for your purposes, perhaps consider specifying what "objects" you're sending to the user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top