Php очистить экран браузера
I would rather it cleared and just showed the latest result. system("command \C CLS") doesnt work. Nor does ob_flush(), flush() or anything else that I've found.
I'm running windows 7 64 bit ultimate, I noticed the command line outputs in real time, which was unexpected. Everyone warned me that out wouldn't. but it does. a 64 bit perk?
Cheers for the help!
I want to avoid echoing 24 new lines if I can.
I tried delete 0x7F however I get a small triangle instead of a deletion. I could use backspace, but the cursor is at the start of the line.
12 Answers 12
Try outputting a line of text and terminating it with "\r" instead of "\n".
The "\n" character is a line-feed which goes to the next line, but "\r" is just a return that sends the cursor back to position 0 on the same line.
Make sure to output some spaces before the "\r" to clear the previous contents of the line.
[Edit] Optional: Interested in some history & background? Wikipedia has good articles on "\n" (line feed) and "\r" (carriage return)
This looks like it could work well. For anyone else I plan on capturing the length of each output to ensure that enough output is provided to erase the previous output.
I'd suggest putting the \r at the front and end of the buffer, that way if the user inputs something (between the buffers), it doesn't get prepended to the next buffer.
+1 One of the rare advantages of the double-character newline. Seems there is a use in the modern age for the carriage return (CR) as well as the line feed (LR). Once this was exploited heavily in terminal-based software, old methods. I guess people do not learn their control characters any more, one of the first things I really had to learn!
This wont work across multiple lines unfortunately as the \r will only return the cursor to the start of the current line.
Does not work for strings that wrap. Also, why not just use "\r" for return to beginning of line? Works for both platforms.
I recently wrote a function that will also keep track of the number of lines it last output, so you can feed it arbitrary string lengths, with newlines, and it will replace the last output with the current one.
With an array of strings:
One can use the following function:
And all lines replace each other.
The name of the function could use some work, just whipped it up, but the idea is sound. Feed it an (int) as the second param and it will replace that many lines above instead. This would be useful if you were printing after other output, and you didn't want to replace the wrong number of lines (or any, give it 0).
Dunno, seemed like a good solution to me.
I make sure to echo the ending newline so that it allows the user to still use echo / print_r without killing the line (use the override to not delete such outputs), and the command prompt will come back in the correct place.
Я создал динамическую веб-страницу. На главной странице есть три скользящих изображения. Я создал другую страницу, чтобы изменить изображение главной страницы (скользящее). Поэтому после отправки второй страницы я написал код PHP, чтобы вернуться на главную страницу. Но изображения не меняются, потому что мой браузер имеет эту веб-страницу в своем кэше. Если я удаляю кеш вручную или перезагружаю браузер, он работает. Как удалить кеш браузера в кодировке PHP? дай мне решение. Благодарю.
Решение
Попробуйте использовать элемент управления HTML-кешем META TAGS:
или используйте EXPIRES:
Другие решения
Вы не можете очистить кеш, однако вы можете попросить страницу не кешировать в первую очередь:
Об этом уже спрашивали в StackOverflow, и этот ответ был взят оттуда исключительно для того, чтобы поблагодарить такого же пользователя, который уже ответил на этот вопрос.
Или, как уже было сказано, вы можете использовать для этого теги META, но вы попросили PHP-решение, поэтому вот оно: D
Вы также можете добавить случайную строку в image-URI:
Если случайная строка меняется каждый раз, главная страница перезагружается (!), Браузер получит изображение с сервера.
Есть один прием, который можно использовать. Он заключается в добавлении параметра / строки к имени файла в теге сценария и изменении его при внесении изменений в файл.
Браузер интерпретирует всю строку как путь к файлу, даже несмотря на то, что идет после «?» параметры. Так что теперь происходит то, что в следующий раз, когда вы обновите свой файл, просто измените номер в теге script на вашем сайте (пример ) и каждый пользовательский браузер увидит, что файл изменился, и получит новую копию.
Если ваши файлы часто меняются, на вашем месте я бы просто отправил следующий заголовок вместе с PHP:
Вы можете добавить эти строки непосредственно перед первым выпуском вашего PHP-скрипта на свои страницы. При этом вы говорите браузеру, что он не должен кэшировать страницу и должен каждый раз запрашивать содержимое.
Эта функция отправит содержимое буфера вывода (если имеется). Если необходима дальнейшая обработка буфера вывода, то следует вызвать ob_get_contents() перед ob_flush() , так как содержимое буфера будет удалено после вызова ob_flush() .
Эта функция не уничтожает буфер вывода, как это делает ob_end_flush() .
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Смотрите также
User Contributed Notes 14 notes
As of August 2012, all browsers seem to show an all-or-nothing approach to buffering. In other words, while php is operating, no content can be shown.
In particular this means that the following workarounds listed further down here are ineffective:
1) ob_flush (), flush () in any combination with other output buffering functions;
2) changes to php.ini involving setting output_buffer and/or zlib.output_compression to 0 or Off;
3) setting Apache variables such as "no-gzip" either through apache_setenv () or through entries in .htaccess.
So, until browsers begin to show buffered content again, the tips listed here are moot.
some problems with ob_flush() and flush() could be resolved by defining content type header :
header( 'Content-type: text/html; charset=utf-8' );
so working code looks like this:
header ( 'Content-type: text/html; charset=utf-8' );
echo 'Begin .
' ;
for( $i = 0 ; $i < 10 ; $i ++ )
echo $i . '
' ;
flush ();
ob_flush ();
sleep ( 1 );
>
echo 'End .
' ;
?>
Although browsers now have an all or none buffering strategy, the arguments are not moot.
If you are not using ob_flush, you run this risk of exceeding socket timeouts (commonly seen in php-fpm/nginx combos).
Basically, flushing solves the infamous 504 Gateway Time-out error.
If there is no active output buffer, an error of level E_NOTICE is generated (at least in PHP 7.1). To avoid this, test first with `ob_get_level()`.
If you call ob_flush() and flush() and still dont get the buffer flushed it might be because some antivirus software (Panda in this case) holds the buffer until the page has finished loaded before sending it to the browser.
If you're still not getting the buffer work correctly then try to clean all the others before starting your own (and even if PHP tells you that there are no buffers active):
I was having problems with output buffering which seemed to be active by default on the server, although phpinfo said something else..
In any case I needed to know that when I ran ob_start, it would start at the top level, so I could use ob_flush as it's intended without having to call multiple ob_flush in-script - this is what I did:
// make sure output buffering is off before we start it
// this will ensure same effect whether or not ob is enabled already
while ( ob_get_level ()) ob_end_flush ();
>
// start output buffering
if ( ob_get_length () === false ) ob_start ();
>
?>
Then I could call ob_flush(); followed by flush(); and get the output I wanted, which I didn't if I started the script with just ob_start();
This was on a windows apache 2 server with php 5.0.4 btw.
For some reason, calling just flush or ob_flush or even both together did not get my output buffers flushed, and calling ob_end_flush by itself didn't work either but calling them all worked well. Here is my new output flushing function.
function flush_buffers () <
ob_end_flush ();
ob_flush ();
flush ();
ob_start ();
>
?>
Enjoy
As stated in flush() manual entry, if php compresses the ouput with zlib this function may be ineffective.
A possible option for folders on your server that have scripts which may take a long time to run is to add the following in your relevant .htaccess file:
php_flag zlib.output_compression off
php_value max_execution_time 3000
php_value max_input_time 3000
Currently I have Chrome on OS X Snow Leopard updating a page as it is sent more data, BUT it only does this after I send it
along with 1013 more characters (making 1019 total characters). After it receives this it immediately displays it and then displays anything else as it is received. (Note that this browser-operating system combination isn't necessarily the only one, it's just the only one I've tested.)In order to do this using php, I've done nothing but send ob_flush() after each echo or print. I can also make it happen without ob_flush() by calling ob_implicit_flush(), then ob_end_flush() before print, and then it updates with each print after that. I have pretty typical settings and I change none of them when the file runs, it literally looks like this:
ob_implicit_flush ();
ob_end_flush ();
?> [1013 more characters] for ( $i = 1 ; $i < 30000000 ; ++ $i ) <>
echo "something that didn't show up immediately" ;
?>
(Ok, the "[1013 more characters]" part wasn't strictly literal.)
If you want just text in the browser, you do this before everything else:
header ( "Content-type: text/plain" );
.
?>
Then it won't care whether you sent a body tag, it will just wait for 1019 characters.
when using command line php, if somewhere in your script you have ob_start(), you have to call ob_end_flush() first, and then you can call these functions:
flush();
ob_flush();
without calling ob_end_flush first, flush and ob_flush does not have any effect, at least that's what I experienced.
we had problems with flushing data to the browser. a simple call to ob_flush() or flush() would not work. We found that repeatly calling theses fuctions did work however.
Also note that any data in the buffer will flush at the end of the script, not destroyed, so it is often not necessary to call ob_flush(); for example:
ob_start ();
echo 'Hello World!'
?>
Will still result in Hello World! being displayed to the browser.
Функция очищает системный буфер вывода PHP, при этом всё содержимое буфера отправляется в браузер пользователя (с некоторыми исключениями), независимо от используемого бекенда PHP (CGI, веб-сервер и т.д.).
flush() не сможет переопределить схему буферизации вашего веб-сервера и никак не влияет на буферизацию браузера на стороне клиента. Функция также не влияет на механизм буферизации пользовательского PHP-кода. Это означает, что ob_flush() должен быть вызван перед flush() , чтобы очистить выходные буферы, если они используются.
Некоторые серверы, особенно под управлением Win32, будут по-прежнему продолжать буферизировать вывод вашего скрипта до передачи результатов в браузер.
Серверные модули для Apache, такие как mod_gzip, могут сами выполнять буферизацию, поэтому flush() не приводит к немедленной передаче данных клиенту.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Смотрите также
User Contributed Notes 36 notes
This will show each line at a time with a pause of 2 seconds.
(Tested under IEx and Firefox)
if ( ob_get_level () == 0 ) ob_start ();
echo "
Line to show." ;
echo str_pad ( '' , 4096 ). "\n" ;
This is what I use to turn off pretty much anything that could cause unwanted output buffering and turn on implicit flush:
@ apache_setenv ( 'no-gzip' , 1 );
@ ini_set ( 'zlib.output_compression' , 0 );
@ ini_set ( 'implicit_flush' , 1 );
for ( $i = 0 ; $i < ob_get_level (); $i ++) < ob_end_flush (); >
ob_implicit_flush ( 1 );
?>
If it still fails though, keep in mind that Internet Explorer and Safari have a 1k buffer before incremental rendering kicks in, so you'll want to output some padding as well.
I would like to point out that there is a function to replace ob_flush and flush. If you set ob_implicit_flush(true); at the top of the page it will automatically flush any echo or print you do in the rest of the script.
Note that you still need a minimum amount of data to come through the browser filter. I would advice using str_pad($text,4096); since this automatically lenghtens the text with spaces to 4 KB which is the minimum limit when using FireFox and linux.
I hope this helps you all out a bit.
This is an extention of Rusty's comment below:
After sitting here for hours trying to make IE6 flush data out in the middle of a page (with it working perfectly in Firefox), I finally figured out the problem. IE will not display flushed data (even if it has it) unless the table that contains it is complete.
Every new element you want IE to display must not be in ANY kind of table at all. You must end all your tables.
For a Windows system using IIS, the ResponseBufferLimit takes precedence over PHP's output_buffering settings. So you must also set the ResponseBufferLimit to be something lower than its default value.
For IIS versions older than 7, the setting can be found in the %windir%\System32\inetsrv\fcgiext.ini file (the FastCGI config file). You can set the appropriate line to:
ResponseBufferLimit=0
For IIS 7+, the settings are stored in %windir%\System32\inetsrv\config. Edit the applicationHost.config file and search for PHP_via_FastCGI (assuming that you have installed PHP as a FastCGI module, as per the installation instructions, with the name PHP_via_FastCGI). Within the add tag, place the following setting at the end:
responseBufferLimit="0"
So the entire line will look something like:
Alternatively you can insert the setting using the following command:
%windir%\system32\inetsrv\appcmd.exe set config /section:handlers "/[name='PHP_via_FastCGI'].ResponseBufferLimit:0"
Hi all.
Been scratching my head over data NOT flushed to IE (6) even though I tried strpad 4096 chars, all headers OK, TABLE and no TABLE, flush and ob_flush - still a blank page. Tried adding a sleep(1) before flushing - and everything worked as a charm.
When using PHP with mode CGI/FastCGI there is a new buffer (initiated by mod_fcgid with a default size of 65536 bytes). That causes `flush()` and `ob_flush()` not working as expected with implicit_flush(true).
Setting "OutputBufferSize 0" in mod_fcgid config resolves the issue.
Hope it helps !
Not the other way around, because it wont work.
Like IE, Safari needs a fair amount of data before it'll display anything, actually more than explorer. The following code works for me in Firefox and Safari, and should work in IE as well.
for( $i = 0 ; $i < 40000 ; $i ++)
echo ' ' ; // extra spaces
>
// keeps it flowing to the browser?
flush ();
// 50000 microseconds keeps things flowing in safari, IE, firefox, etc
usleep ( 50000 );
?>
This code came from a comment on a blog discussing browser functionality with flush();
After searching through the PHP site, google and various forums, not finding a solution to my script not outputting anything while calling flush and ob_flush, I thought of trying to tell PHP to call:
before starting echo'ing. It worked like a charm. I couldn't find any references to this, so I hope this note will help someone in the future.
I've spent days trying to figure out why flush didn't work all of a sudden, while it used to work perfectly. Apparently, it was McAfee Spamkiller that caused problems. Disabling it didn't work, I had to completely remove it. Hope this helps someone.
It is a bit complicated to work with the funktion flush() and you have to experiment with it a bit.
So if you design a site which has a timeloop at the end that calls a other site via a form data input (Data Submit) you have
to give something out to the buffer to get that new site loaden quick.
$instant = gettimeofday ();
$timenow = $instant [ "sec" ]; //Start Time
//timeloop(e.g. for security_save after 30 min)
while ( 1 ) " ; //Useless (only to quickload next
//or same Site when do a switch)
flush (); //giveout buffer
$instant = gettimeofday ();
$timeactual = $instant [ "sec" ]; //get Actual Time in Secs
$flag =(( $timeactual > $timenow + $diff )? 1 : 0 ); //$diff=switchTime
if ( $flag ) < what_do_at_switch_Time (); //Sec.Save etc.etc.
$timenow = $timeactual ; > //Set new Start Time
sleep ( 5 ); //Or so. (Important)
> //End of while-Loop
?>
So you can programm a security save or other function in your site and if you do a switch the upload of the new or same site (the called site) works.
combining some ideas i was finally able to get a long running script to give me real time feedback on what it was doing. this was a wamp setup with php running as cgi. i'm pretty sure that apache just wasn't sending any of the buffered output because it was trying to be helpful. also trying to be helpful, i hope this example solution helps someone.
// thx mandor at mandor
ini_set ( 'max_execution_time' , 0 );
ini_set ( 'implicit_flush' , 1 );
ob_implicit_flush ( 1 );
echo 'doing something' ; my_flush ();
sleep ( 5 );
echo 'doing something else' ; my_flush ();
sleep ( 5 );
echo 'finally done - hooray' ;
function my_flush () // following matt at hevanet's lead
for ( $i = 0 ; $i < 10000 ; $i ++) echo ' ' ;
ob_flush ();
flush ();
>
I had a bunch of problems trying to get flush working on my windows box, I finally found a solution after reading everyones here and it not working.
1) Set output_buffering = 0
2) Set zlib.output_compression = 0
I then used Wireshark to monitor network packets, and indeed the server was pusing the data, but the browser was not displaying it.. So it was a browser buffer issue (I am on Firefox 13)
For me I needed to send about 1k of data before it would display the data. To do this I added more header information..
In php.ini I set default_charset = "utf-8"
And that was enough to give me enough for the buffer issue.
You can also try doing
echo str_repeat(" ", 1024), "\n";
at the start of the script.
hope this helps
If flush() function does not work. You must set next options in php.ini like:
--[code]--
output_buffering = Off
;output_handler =
zlib.output_compression = Off
;zlib.output_handler =
--[^code^]--
If things does not work you must view headers from the server and check `Server` string.
In my case, as the frontend was Nginx webserver and Apache work as backend.
Accordingly, buffering must be disabled in Nginx config file.
To stop buffering you must add next string to config file:
and restart Nginx daemon. More information about configuration you find in documentation on the nginx website.
If you're not explictly using the buffering functions, then ob_flush() is only necessary if output buffering is turned on in your php.ini file.
flush() is only necessary if implicit_flush is turned off in your php.ini file. Setting implicit_flush to on will remove the need for all these flush() calls, but it's generally only good in an extremely controlled environment. Turning on implicit_flush in a production environment can be bad.
On Windows xampp 1.3 with php 4.3.4 is use this functions
to force a flush.
function dummyErrorHandler ( $errno , $errstr , $errfile , $errline ) <
>
function forceFlush () <
ob_start ();
ob_end_clean ();
flush ();
set_error_handler ( "dummyErrorHandler" );
ob_end_flush ();
restore_error_handler ();
>
?>
ob_end_flush generates a warning, which is supressed, using the dummy-errorhander. You could also use @, but then nusphere will also print the warning.
These values can be appended to the directive, e.g. or in ProxyPass and ProxyPassMatch lines.
The mod_proxy_fcgi documentation for 2.4 does not document this, but it is available in the 2.5 or trunk documentation.
Regarding buffering by browser you can use:
Works for me in Firefox 60 ESR.
This helped me getting flushing to work.
Using apache with deflate.
Turning compression off for this script: (add it somewhere at the top of the script)
apache_setenv('no-gzip', '1');
However, this only works if php is running as a module rather than a cgi-extension and safe mode must be disabled.
You can also turn the compression off for a directory by making a .htaccess file and adding the following entry:
mod_gzip_on Off
However that affects the whole directory.
Hope I could help.
I had the same problems with sending a javascript after the content has been sent to the browser (the script updates the content of an iframe).
Two solutions work for me:
- add enough data (i.e.: extra dummy text like spaces) or,
- echo the '' tag at the end of the page
Note, that for the latter to work one should:
- turn of output_buffering in php.ini and either:
* turn on implicit_flush in its php.ini or,
* call ob_implicit_flush(); at the beginning of a script
I preferr echoing the '