Ob_start - Включение буферизации вывода. Использование ob_start при поддержке проектов на php

(PHP 4, PHP 5, PHP 7)

ob_start — Включение буферизации вывода

Описание

Bool ob_start ([ callable $output_callback = NULL [, int $chunk_size = 0 [, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS ]]])

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

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

Внимание

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

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

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

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

String handler (string $buffer [, int $phase ])

Buffer Содержимое буфера вывода. phase Битовая маска констант PHP_OUTPUT_HANDLER_* .

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

Параметр output_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-функций буферизации вывода.

Замечание :

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

chunk_size

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

До PHP 5.4.0, значение 1 было специальным значением, которое устанавливало параметр chunk_size в 4096.

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

Each flag controls access to a set of functions, as described below:

Константа Функции
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 в случае возникновения ошибки.

Список изменений

Версия Описание
7.0.0 В случае, если ob_start() используется внутри callback-функции буфера вывода, эта функция больше не будет приводить к ошибке E_ERROR , а вместо этого будет вызывать E_RECOVERABLE_ERROR , позволяя сторонним обработчикам ошибок поймать ее.
5.4.0 Третий параметр ob_start() изменен с булева (boolean ) параметра erase (который при установке в FALSE предотвращал удаление буфера до тех пор, пока не завершалась работа скрипта) на целочисленный (integer ) параметр flags . К сожалению, это означает появление несовместимости API для кода, который использовал третий параметр до версии PHP 5.4.0. Смотрите пример с флагами , чтобы понять как работать с кодом, чтобы он поддерживал совместимость с обеими версиями.
5.4.0 Параметр chunk_size , установленный в 1 , теперь приводит к выводу по 1 байту в выходной буфер.
4.3.2 Функция вернет FALSE в случае, если output_callback не сможет быть выполнена.

Примеры

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

Function callback ($buffer )
{
// заменить все яблоки апельсинами
return (str_replace ("яблоки" , "апельсины" , $buffer ));
}

Ob_start ("callback" );

?>


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




ob_end_flush ();

Привет, Хабр!

Сегодня я бы хотел познакомить начинающих вебмастеров с разнообразными изящными способами использования буферизации вывода в php. Опытные вебмастера для себя здесь врят ли найдут что-то полезное. Хотя - кто знает?

Как вы все знаете, буферизацией вывода в php управляет набор функций, начинающихся на «ob_». Самая главная из них - ob_start. При запуске она собирает последующий вывод, то есть всевозможные print(), echo и прочее, что потом отдастся посетителю в форме html-странички. И если перед тем, как выводить, мы запустили буферизацию, то с этой, почти готовой уже, страничкой, можно будет напоследок что-нибудь сотворить.


Например, мы хотим отфильтровать все ссылки на посторонние сайты.

На нашем, древнем как топор австралопитека, форуме, роится великое множество спамеров, заманивающих посетителя в места, заполненные развратом, однорукими бандитами и политической агитацией. Можно было бы использовать js со слежением, но мы хотим вместо этого изменить все эти ссылки так:

"http://blackjack-hookers.com" => "http://myoldforum.ru/redirect.php?url=blackjack-hookers.com"

Способ может быть и не самый эффективный, но действенный. Мы написали redirect.php с фильтром и черным листом, и теперь нам надо преобразовывать все ссылки на тысячах страниц форума. С помощью ob_start и парочки регулярных выражений мы сделаем это всего в несколько строк:

Function f_callback($buffer){ $buffer = preg_replace("#http://(www.)?myoldforum\.ru/#","/",$buffer); $buffer = preg_replace("#href="http://([^"]*)"#","#href="/redirect\.php\?url=$1",$buffer); return $buffer; } ob_start(f_callback);

Теперь, подключив этот код в начале index.php, или другого файла, к которому обращается сервер при просмотре страниц, мы получим то, что нам нужно.

Меняя контент таким образом, мы не ограничены рамками методов движка. Это бывает весьма ценно. Можно, например, добавить плагин:

Function generate_plugin(){ /*что-то генерируем*/ } function f_callback($buffer){ /*...*/ $buffer = str_replace ("",generate_plugin(),$buffer); /*...*/ return $buffer; } ob_start("f_callback");

Теперь, там, где мы добавили в контент появится то, что мы хотели получить. Одно из применений - вставка виджета js на страницу сайта. Например, яндекс-карты. Обычно это не составляет никакого труда, но иногда криво написанный редактор страниц сайта экранирует кавычки и фигурные скобки, ломая виджет. Как видим, эта проблема легко решается.

Набор инструментов php для работы с буффером вывода богат, и не ограничивается одним лишь ob_start. Вышеописанные приемы в некоторых случаях излишне ресурсоемки и громоздки, поскольку оперируют со всей страницей. Мы можем обработать только ее часть, создав в шаблоне оболочку вокруг генерации чего-то, в дебри чего нам не хочется лезть, но что обязательно нужно поправить:

{GENERATE BIG CRAZY THING}

Должно быть, вы уже заметили все эти обороты: «не хочется лезть», «древний, как стул тиранозавра», «криво написанный редактор»… В идеальном мире оболочки вокруг буфера вывода не нужны. Все что можно сделать с помощью ob_start, теоретически можно было бы сделать и без него. Этот прием иной раз вносит путанницу в код проекта, многие видят его смысл лишь в том, что бы отдать вывод в ob_gzhandler для сжатия, и считают его применение в иных случаях опасным. Но часто без управления выводом просто не обойтись.

Особенно если не хочется копать вглубь.

The substr() function returns a part of a string.

Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

Syntax

substr(string,start,length )


Parameter Description
string Required. Specifies the string to return a part of
start Required. Specifies where to start in the string
  • A positive number - Start at a specified position in the string
  • A negative number - Start at a specified position from the end of the string
  • 0 - Start at the first character in string
length Optional. Specifies the length of the returned string. Default is to the end of the string.
  • A positive number - The length to be returned from the start parameter
  • Negative number - The length to be returned from the end of the string

Technical Details

Return Value: Returns the extracted part of a string, or FALSE on failure, or an empty string
PHP Version: 4+
Changelog: In PHP Version 5.2.2 to 5.2.6, if the start parameter indicates the position of a negative truncation or beyond, FALSE is returned. Other versions get the string from start

More Examples

Example 1

Using the start parameter with different positive and negative numbers:

echo substr("Hello world",10)."
";
echo substr("Hello world",1)."
";
echo substr("Hello world",3)."
";
echo substr("Hello world",7)."
";

echo substr("Hello world",-1)."
";
echo substr("Hello world",-10)."
";
echo substr("Hello world",-8)."
";
echo substr("Hello world",-4)."
";

PHP provides several functions that search for one string within another. Some return the location of the found string (strpos , strrpos and related), and return part of the original string (strstr and strrchr). The search functions return false if the string you are searching for is not found within the original.

If your goal is simply to determine whether one string exists within another, the most efficient option is strpos .

strpos

The strpos function searches its first string argument for its second and returns the zero-based index location of the first match within the string, or false if it is not found. The following example demonstrates:

$str = ; // search for the first occurrence of "need" within $str $pos = strpos ($str , "need" ) ; // display type and value of $pos var_dump ($pos ) ; // int(3)

Although we demonstrated the result using var_dump above, a typical examination of the return value for strpos is performed as follows:

// how to inspect strpos return value ($pos) if ( $pos !== false ) { // if search string found echo "found it at location $pos" ; } else { echo "not found." ; }

Be sure to use the === or !== operators to compare the strpos function"s return value to false . If the substring is found at the start of the string, strpos will return 0 , which the == or != operators would convert to false .

You can specify an offset to begin the search a specified number of characters from the start of the string, as this example demonstrates:

/* strpos arguments: * subject string (aka haystack), search string (needle), offset (optional) */ // start search for "need" from character 10 in $str $pos = strpos ($str , "need" , 10 ) ; // 20

When starting the search from character 10 , the result is 20 , the index location of the start of the word needle .

strrpos

The strrpos function finds the position of the last occurrence of a substring in a string:

// example string to use for searches $str = "We need to find the needle in the haystack." ; // find location of last occurrence of "need" in $str $pos = strrpos ($str , "need" ) ; // 20

The strrpos function also provides an optional offset parameter which can be either positive or negative. If the offset is positive, that number of characters at the beginning of the string will be excluded from the search. Consider the following example:

// search from right for "We" excluding first 3 characters $pos = strrpos ($str , "We" , 3 ) ; var_dump ($pos ) ; // bool(false)

The result is false since "We" is not found when the search excludes the first three characters.

If the offset is negative, that many characters at the end of the string are excluded from the search. We demonstrate with two searches specifying a negative offset:

// search from right for "hay" excluding last 5 characters $pos = strrpos ($str , "hay" , - 5 ) ; // int(34) // search from right excluding last 10 characters $pos = strrpos ($str , "hay" , - 10 ) ; // bool(false)

The last result above is false since "hay" is not found when the search excludes the last 10 characters.

Notice that the return value of the strrpos function gives the location from the start of the string, even though the search commences from the right.

stripos and strripos

The strpos and strrpos functions perform case-sensitive searches. PHP provides stripos and strripos functions to perform case-insensitive searches. They work just like their case-sensitive equivalents:

// example string to use for searches $str = "We need to find the needle in the haystack." ; // do case-insensitive search for "we" $pos = stripos ($str , "we" ) ; // int(0) // do case-insensitive search from right for "Need" $pos = strripos ($str , "Need" ) ; // int(20)

The case-insensitive search for "we" results in 0 , indicating it was found at the beginning of the string we are searching in. The case-insensitive search for "Need" from the right (using strripos), finds it at location 20 .

strstr

The strstr function searches the first string argument for the second. If the second is found within the first, strstr returns the portion of the original string starting from the first found occurrence to the end of the string.

// example string $str = "We need to find the needle in the haystack." ; // search for "the" in $str $newstr = strstr ($str , "the" ) ; var_dump ($newstr ) ; // string(27) "the needle in the haystack."

The strstr function returns the first "the" it finds, along with the rest of the original string.

If you pass true as the third argument to strstr , the portion of the original string before the found string is returned:

// pass true to return the part of $str before "the" $newstr = strstr ($str , "the" , true ) ; var_dump ($newstr ) ; // string(16) "We need to find "

This time the strstr function returns everything before the first "the" in the string.

PHP also provides the stristr function which works exactly the same as strstr except that it performs a case-insensitive search.

strrchr

The strrchr function searches the first string argument from the right for the character we specify in the second argument. The function returns the portion of the string from the location of the found instance of that character to the end of the string:

// example string $str = "We need to find the needle in the haystack." ; // search from right for "s" in $str $newstr = strstr ($str , "s" ) ; var_dump ($newstr ) ; // string(6) "stack."

Notice that unlike strstr , if the second argument consists of multiple characters, only the first is used:

// test with multi-character second argument $newstr = strrchr ($str , "the" ) ; var_dump ($newstr ) ; // string(5) "tack."

Instead of returning "the haystack" , the strrchr function returns "tack" , applying only the first letter of the second argument to the search.