Php output buffer start

Lara L. Schenck

As someone who works with WordPress on the regular, output buffering is one of those concepts that I’ve encountered in the past and, until now, never needed to understand. I hope this serves to be a relatively plain language description of what output buffering is at a high level, and will illuminate the concept for…

tl;dr: Output buffering is a way to tell PHP to hold some data before it is sent to the browser. Then you can retrieve the data and put it in a variable, manipulate it, and send it to the browser once you’re finished.

Umm…isn’t this a little random?

Yes…but no! As someone who works with WordPress on the regular, output buffering is one of those concepts that I’ve encountered in the past and, until now, never needed to understand. It’s a good example of learning on a “need to know” basis which, I think most web folk will agree, is a core part of being in our industry. Particularly when using plugins and frameworks, we constantly come across code where we pause and think, “Uh, I have no idea what that does…” then we move along with our lives. Sometimes, however, we need to understand what that code-written-by-a-smarter-person-than-me is, for whatever reason.

This rabbit hole of research began with a question I received in my inbox regarding Timber, a plugin I love to use when developing custom WordPress websites: “What do header.php and footer.php do in a Timber theme?”

The quick answer to this question is they do nothing; they are required for certain WordPress plugins. But I didn’t know that! I’d never had to touch those files in my development practice, oddly enough, so I began to investigate. The main pieces of code in these files were PHP output buffering functions ( ob_start , ob_get_contents , etc).

Let’s leave the Timber details for another time, and dive into this PHP thing called “output buffering”.

What is output buffering?

What is output buffering? Let’s pretend you, the developer had a conversation with PHP:

You: “Hey, PHP! Don’t send any output to the browser immediately, like you usually do. I want to do some programming stuff to it first, then I’ll tell you when to send it.”

PHP: “Ok, I’ll store it in a thing called a buffer until you tell me when to send it to the browser.”

You: “Thanks, PHP! Don’t worry, you are still relevant.”*

Читайте также:  Php intelephense для чего

In other words, PHP sends data to the browser from the server as soon as a function is finished. For example, if your PHP code is echo «Hi there»; the string “Hi there” is sent to the browser immediately after the echo function runs. If you run that echo function when output buffering is in effect, however, “Hi there” will be stored in this invisible holding cell called a buffer, and won’t display on the page until you’ve retrieved its contents and sent them to the browser.

* In the age of JavaScript this, this, and that, it seems almost futile to write a detailed post about little PHP nuance. But it’s not! For one, PHP is the OG of programming for the web and WordPress, built in PHP, powers 25% of the web at large. JavaScript may be here to stay, but PHP isn’t going anywhere!

The Functions

A few common output buffering functions:

ob_start() turns on output buffering. In other words, it creates the buffer (invisible holding cell) that will store all output after it is called.

ob_get_contents() grabs all of the data gathered since we called ob_start, i.e. everything in the buffer. Usually, you’ll assign this to a variable.

ob_clean() removes everything from the output buffer. Note that it does not output anything.

ob_flush() outputs content from the buffer. Note that it does not erase the buffer.

ob_end_clean() basically runs ob_get_contents() , discards the result, and turns off output buffering.

ob_end_flush() outputs content from the buffer and ends output buffering. It does not erase the buffer.

An Example

The most important part of using the output buffering functions is where you put them. You need to initiate the buffer with ob_start in the right spot, and you need to output the buffer either onto the page or into a variable before you empty it.

But why?

Great question; it’s quite possible you’ll never actually use output buffering unless you are a WordPress plugin developer or write custom PHP applications. For those of us who do neither of those things, here are a few instances where output buffering know-how could come in handy, if not only to provide context for a larger issue:

HTTP Headers

Warning: Cannot modify header information — headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23

Читайте также:  Python parse date format

For anyone unfamiliar with the definition of an HTTP header, HTTP headers are information sent from a server upon an HTTP request that tells the browser what kind of data is coming before it gets there. HTTP headers contain information like the type of content on its way, the date it was last modified, the type of server sending the request, and much more. The catch is, headers need to be sent before any output or other data is sent from the server.

A quick example: Let’s say your application saves a user’s login information in a cookie. Cookies are a type of HTTP header, so they must be sent to the browser before any other site data. Depending on how your program is structured, the cookie code might not be at the very top of your file. Output buffering, in simplest terms, allows you say, “Hey PHP, I’ll tell you when to send the regular site output after I’ve handled the cookie and stuff,” otherwise, you may run into an error similar to the above.

Note that running into this error in the above scenario could indicate some bad practice in terms of how your application is structured, conflicts with other plugins, or something else that is otherwise no bueno. There is a fantastic explantion of this error on StackOverflow here.

In Conclusion

You, front-end developer, might never use output buffering.

But someday, you may need to understand it! And I hope this write-up will help someone somewhere in their debugging adventures.

Resources

Источник

ob_start

Эта функция включает буферизацию вывода. Если буферизация вывода активна, никакой вывод скрипта не отправляется (кроме заголовков), а сохраняется во внутреннем буфере.

Содержимое этого внутреннего буфера может быть скопировано в строковую переменную, используя ob_get_contents() . Для вывода содержимого внутреннего буфера следует использовать ob_end_flush() . В качестве альтернативы можно использовать ob_end_clean() для очистки содержимого буфера.

Некоторые веб-серверы (например, Apache) изменяют рабочую директорию скрипта при вызове callback-функции. Вы можете вернуть её назад, используя chdir(dirname($_SERVER[‘SCRIPT_FILENAME’])) в callback-функции.

Буферы вывода помещаются в стек, то есть допускается вызов ob_start() после вызова другой активной ob_start() . При этом необходимо вызывать ob_end_flush() соответствующее количество раз. Если активны несколько callback-функций, вывод последовательно фильтруется для каждой из них в порядке вложения.

Если буферизация вывода всё ещё активна, когда скрипт завершает работу, PHP автоматически выводит содержимое.

Список параметров

Можно задать необязательный параметр callback . Эта функция принимает строку в виде аргумента и должна также вернуть строку. Она вызывается при сбросе (отправке) или очистке (с помощью ob_flush() , ob_clean() или подобных функций) или если буфер вывода сбрасывается в браузер по окончанию запроса. При вызове функции callback , она получает содержимое буфера и, как ожидается, должна вернуть обновлённое содержимое для буфера вывода, которое будет отправлено браузеру. Если callback не является допустимой функцией, то эта функция вернёт false . Описание функции для этого параметра:

Читайте также:  Определить тип объекта javascript

Если callback вернёт false , то оригинальная информация отправится в браузер без изменений.

Параметр callback может быть игнорирован передачей значения null .

ob_end_clean() , ob_end_flush() , ob_clean() , ob_flush() и ob_start() не могут вызываться из callback-функций, так как их поведение непредсказуемо. Если вы хотите удалить содержимое буфера, то верните «» (пустую строку) из callback-функции. Вы также не можете использовать функции буферизации вывода, такие как print_r($expression, true) или highlight_file($filename, true) из callback-функции.

Замечание:

Функция ob_gzhandler() была введена для облегчения отправки gz-кодированных данных браузерам, поддерживающим сжатые веб-страницы. ob_gzhandler() определяет тип кодировки содержимого, принимаемый браузером, и возвращает вывод соответствующим образом.

Если передан необязательный параметр chunk_size , то буфер буден сброшен после любого вывода, превышающего или равного по размеру chunk_size . Значение по умолчанию 0 означает, что функция вывода будет вызвана, когда буфер будет закрыт.

Параметр flags является битовой маской, которая управляет операциями, которые можно совершать над буфером вывода. По умолчанию она позволяет буферу вывода быть очищенным, сброшенным и удалённым, что равносильно значению PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE или PHP_OUTPUT_HANDLER_STDFLAGS как сокращение этой комбинации.

Каждый флаг управляет доступом к набору функций, как описано ниже:

Константа Функции
PHP_OUTPUT_HANDLER_CLEANABLE ob_clean() , ob_end_clean() и ob_get_clean() .
PHP_OUTPUT_HANDLER_FLUSHABLE ob_end_flush() , ob_flush() и ob_get_flush() .
PHP_OUTPUT_HANDLER_REMOVABLE ob_end_clean() , ob_end_flush() и ob_get_flush() .

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример callback-функции, определённой пользователем

function callback ( $buffer )
// заменить все яблоки апельсинами
return ( str_replace ( «яблоки» , «апельсины» , $buffer ));
>

Результат выполнения данного примера:

  

Это всё равно что сравнить апельсины и апельсины.

Пример #2 Создание нестираемого буфера вывода

ob_start ( null , 0 , PHP_OUTPUT_HANDLER_STDFLAGS ^ PHP_OUTPUT_HANDLER_REMOVABLE );

Смотрите также

  • ob_get_contents() — Возвращает содержимое буфера вывода
  • ob_end_clean() — Очистить (стереть) буфер вывода и отключить буферизацию вывода
  • ob_end_flush() — Сбросить (отправить) буфер вывод и отключить буферизацию вывода
  • ob_implicit_flush() — Включение/выключение неявного сброса
  • ob_gzhandler() — callback-функция, используемая для gzip-сжатия буфера вывода при вызове ob_start
  • ob_iconv_handler() — Преобразует символы из текущей кодировки в кодировку выходного буфера
  • mb_output_handler() — Callback-функция, преобразующая кодировку символов в выходном буфере
  • ob_tidyhandler() — Функция обратного вызова ob_start для восстановление буфера

Источник

Оцените статью