简体   繁体   中英

How to use ob_* to set the content length in the header?

I am trying to create a webservice in Yii. The web service is working fine but what i am concerned about is how to use ob_start() group all together so that i could set the Content-length in the header. I read a lot about ob_* group but still i am very much confused about it.
Suppose this is the web service

public function giveTimestamp()
        {
            $query='select current_timestamp( );';
            $record=  Yii::app()->db->createCommand($query)->queryScalar();
            return $record;
        }

Now what I am trying to do is that I will set the content length of the header while sending this data. Now the at client side user will check if he has received the data of the told length. if not then he will send the request again otherwise there will be no request.

SO how can i use this ob_* in combination.?

To get output size in header, you need to have access to output block:

ob_start(); // enable buffering

echo 'content'; // do the output to memory

header('Content-Length: ' . ob_get_length()); // send header

ob_end_flush(); // send content of buffer and terminate it

However, I can not help you with Yii part, as I do not have experience of work with it.

There are two Yii ways of doing this.

  1. Use afterRender to add the header. This will affect every action in a controller unless you work around that, so use cautiously. http://www.yiiframework.com/doc/api/1.1/CController#afterAction-detail

  2. Use a custom filter and apply it as needed to all actions or select actions. I would probably go this route, as you have more flexibility in the future. Another choice is whether to use an inline filter (much like afterRender above or a class-based filter). Class-based makes it easier to apply your filter across controllers. http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM