sonyps4.ru

Несчастный upcoming php.

Статус соединения сохраняется внутренними механизмами PHP. Ниже перечислены четыре возможные состояния:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT
  • 3 - ABORTED и TIMEOUT

Во время штатного выполнения PHP-скрипта установлен статус NORMAL. В случае, если удаленный клиент разорвал соединение, статус изменяется на ABORTED. Чаще всего отсоединение удаленного клиента происходит при нажатии кнопки "Stop" в браузере. В случае, если достигается установленный временной лимит (ознакомьтесь с функцией set_time_limit() ), будет установлен статус TIMEOUT.

Вы можете решать, приводит ли отключение клиента к завершению вашего скрипта. Иногда бывает необходимо, чтобы скрипт выполнился до конца, даже если отсутствует удаленный браузер, которому адресован весь вывод. По умолчанию скрипт завершает свою работу при отключении клиента. Это поведение может быть изменено при помощи опции ignore_user_abort в конфигурационном файле php.ini . Такого же результата можно добиться, указав php_value ignore_user_abort в конфигурационном файле Apache httpd.conf или воспользовавшись функцией ignore_user_abort() . Если вы явно не указали на необходимость игнорировать разрыв соединения с клиентом, выполнение скрипта будет прервано. Исключением является тот случай, если используя register_shutdown_function() , вы указали специальную функцию, вызываемую при завершении скрипта. В таком случае после того, как пользователь нажал кнопку "Stop" в своем браузере, при первой же попытке что-либо вывести PHP обнаруживает, что соединение с клиентом было утеряно, и вызывает завершающую функцию. Эта функция также вызывается при нормальном завершении работы вашего скрипта, поэтому для того, чтобы выполнить некоторые специфические действия при отсоединении клиента, вам понадобится функция connection_aborted() , которая возвращает TRUE , если соединение было разорвано.

Выполнение вашего скрипта также может быть прервано встроенным таймером. Стандартное ограничение по времени составляет 30 секунд, изменить его можно при помощи директивы max_execution_time в конфигурационном файле php.ini . Такого же результата можно достичь, добавив php_value max_execution_time в конфигурационный файл Apache httpd.conf или воспользовавшись функцией set_time_limit() . При достижении скриптом временного лимита выполнение скрипта прерывается и вызывается завершающая функция, если она была указана. Уточнить причину завершения скрипта вы можете при помощи функции connection_status() , которая возвращает 2, если скрипт был прерван по достижению временного ограничения.

Единственное, что следует заметить - что оба статуса: ABORTED и TIMEOUT, - могут быть установлены одновременно. Это может произойти в том случае, если вы явно указали необходимость игнорировать отсоединение удаленного клиента. В таком случае после разрыва соединения, отметив этот факт, PHP продолжит выполнение скрипта, и при достижении временного лимита будет вызвана завершающая функция, если таковая была указана. В этой точке вы можете обнаружить, что connection_status() вернет значение 3.

9 years ago

Hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else.

When using the codes, it nearly drive me mad and I found another thing that may affect the codes:

Content-Encoding: gzip

This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over.

So, it may need to send the header to prevent this problem.

now, the code becomes:

ob_end_clean ();
header ("Connection: close\r\n" );

ignore_user_abort (true ); // optional
ob_start ();
echo ("Text user will see" );
$size = ob_get_length ();

ob_end_flush (); flush (); // Unless both are called !
ob_end_clean ();

//do processing here
sleep (5 );


//do some processing
?>

12 years ago

Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection.

sts at mail dot xubion dot hu
Posted the original solution:


ob_start ();
phpinfo ();
$size = ob_get_length ();
header ("Content-Length: $size " );
ob_end_flush ();
flush ();
sleep (13 );
error_log ("do something in the background" );
?>

Which works fine until you substitute phpinfo() for
echo ("text I want user to see"); in which case the headers are never sent!

The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information.

ob_end_clean ();
header ("Connection: close" );
ignore_user_abort (); // optional
ob_start ();
echo ("Text the user will see" );
$size = ob_get_length ();
header ("Content-Length: $size " );
ob_end_flush (); // Strange behaviour, will not work
flush (); // Unless both are called !
// Do processing here
sleep (30 );
echo("Text user will never see" );
?>
Just spent 3 hours trying to figure this one out, hope it helps someone:)

Tested in:
IE 7.5730.11
Mozilla Firefox 1.81

9 years ago

PHP changes directory on connection abort so code like this will not do what you want:

function abort ()
{
if(connection_aborted ())
unlink ("file.ini" );
}

?>

actually it will delete file in apaches"s root dir so if you want to unlink file in your script"s dir on abort or write to it you have to store directory
function abort ()
{
global $dsd ;
if(connection_aborted ())
unlink ($dsd . "/file.ini" );
}
register_shutdown_function ("abort" );
$dsd = getcwd ();
?>

5 years ago

I had a lot of problems getting a redirect to work, after which my script was intended to keep working in the background. The redirect to another page of my site simply would only work once the original page had finished processing.

I finally found out what was wrong:
The session only gets closed by PHP at the very end of the script, and since access to the session data is locked to prevent more than one page writing to it simultaneously, the new page cannot load until the original processing has finished.

Solution:
Close the session manually when redirecting using session_write_close():

ignore_user_abort (true );
set_time_limit (0 );

$strURL = "PUT YOUR REDIRCT HERE" ;
header ("Location: $strURL " , true );

header ("Content-Encoding: none\r\n" );

Flush ();
ob_flush ();

Session_write_close ();

// Continue processing...

Sleep (100 );
exit;
?>

But careful:
Make sure that your script doesn"t write to the session after session_write_close(), i.e. in your background processing code. That won"t work. Also avoid reading, remember, the next script may already have modified the data.

So try to read out the data you need prior to redirecting.

14 years ago

The point mentioned in the last comment isn"t always the case.

If a user"s connection is lost half way through an order processing script is confirming a user"s credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process.

I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user"s connection dropped during the processing phase... and their card was charged, but they weren"t added to my local DB.

So, it"s always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not.

11 years ago

In regards of posting from:
arr1 at hotmail dot co dot uk

if you use/write sessions you need to do this before:
(otherwise it does not work)

session_write_close();

ignore_user_abort(TRUE);
instead of ignore_user_abort();

2 years ago

The CONNECTION_XXX constants that are not listed here for some reason are:

0 = CONNECTION_NORMAL
1 = CONNECTION_ABORTED
2 = CONNECTION_TIMEOUT
3 = CONNECTION_ABORTED & CONNECTION_TIMEOUT

Number 3 is effectively tested like this:
if (CONNECTION_ABORTED & CONNECTION_TIMEOUT)
echo "Connection both aborted and timed out";

7 years ago

This simple function outputs a string and closes the connection. It considers compression using "ob_gzhandler"

It took me a little while to put this all together, mostly because setting the encoding to none, as some people noted here, didn"t work.

function outputStringAndCloseConnection2 ($stringToOutput )
{
set_time_limit (0 );
ignore_user_abort (true );
// buffer all upcoming output - make sure we care about compression:
if(! ob_start ("ob_gzhandler" ))
ob_start ();
echo $stringToOutput ;
// get the size of the output
$size = ob_get_length ();
// send headers to tell the browser to close the connection
header ("Content-Length: $size " );
header ("Connection: close" );
// flush all output
ob_end_flush ();
ob_flush ();
flush ();
// close current session
if (session_id ()) session_write_close ();
}
?>

6 years ago

I was quite stuck when trying to make my script redirect the client to another URL and then continue processing. The reason was php-fpm. All possible buffer flushes did not work, unless I called fastcgi_finish_request();

// redirecting...
ignore_user_abort (true );
header ("Location: " . $redirectUrl , true );
header ("Connection: close" , true );
header ("Content-Length: 0" , true );
ob_end_flush ();
flush ();
fastcgi_finish_request (); // important when using php-fpm!

Sleep (5 ); // User won"t feel this sleep because he"ll already be away

// do some work after user has been redirected
?>

Last modified on February 24th, 2017 by Vincy.

Like other languages, PHP sleep() is also used to pause program execution for a particular amount of time. This sleeping time could be controlled by a parameter, sending as an argument to this function.

PHP sleep() accepts only one and mandatory argument denoting the period of time, for what, the PHP code execution invoking this function, should be paused. This parameter should be in integer data type. And this integer value specifies the number of seconds to be passed while putting the program execution into sleep.

Some languages like Javascript, not having direct functions like sleep, people might obtain sleep operation by using a loop, XMLHTTP request and etc. And sometimes, people who are new to PHP may also use for holding program execution for a while, with the required amount of time in seconds. This will be done by a lot of work, like, using for getting current and manipulating them to set a limit for running loops to let the program to wait for loop execution and thereby simulating sleep().

Example: PHP sleep()

Let us have a PHP example program with sleep() function pausing execution with specified amount of time.

Putting into sleep at: " . date("H:i:s") . "
"; sleep($sleep_time); echo "waked up after $sleep_time seconds. Current Time is: " . date("H:i:s") . "
"; ?>

Seeing technologies you love move forward is an exciting feeling. Another version brings hope of better integrated tools, increased security, and faster ways to complete core tasks, thus making your web application quicker. PHP6"s improvements and and updates are sure to make PHP6 the best version yet.

register_globals, safe_mode, and quote options Removed

register_globals, being the most significant removal, presents a giant security risk as it allows users to modify the querysting to add, change, and remove variable values. It"s highly recommended that you turn this value off on your present PHP build. Magic quotes functions, most notable magic_quotes_gpc() and magic_quotes() , affect GET, POST, and COOKIE variables. I recommend turning this setting off as well.

Integrated Alternative PHP Cache (APC)

Though this setting will default to off, APC"s caching can significantly increase the speed of your web application. There are currently some great PHP caching libraries available but integrated support can make the system run faster. You can find more information on APC at http://pecl.php.net/package/APC .

E_STRICT Messages Merged with E_ALL

This move will encourage better programming practices. Of course, you will need to set your error_reporting()

String Indexes: {} Removed, Becomes Standard Use

As of PHP6, you will no longer be able to use {} to reference the value of a String"s character at a specified position -- the standard array position syntax, , will become the only usage.

ASP Style Tags Removed (<% %>)

I have no idea why these were ever implemented. I"ve never used them, nor will I ever.

Increased Unicode Support

PHP does not presently provide adequate Unicode support and PHP6 aims to fix that. Unicode is treated on a per-request basis and cannot be used globally throughout PHP"s functionality -- Unicode in PHP becomes inconsistent in usage and takes up more resources.

Other PHP6 Changes:

  • "var" will become an alias of "public" without an E_STRICT warning.
  • GD1 and FreeType1 versions will be removed.
  • Fast CGI will always be on.
  • HTTP_*_VARS variable will be removed.
  • XMLReader and XMLWriter will be integrated.
  • 64-bit integers will be added.
  • Ternary "?" valuable will not be required ($myvar = $_POST["myvar"] ?: "myvalue";)
  • foreach multidimensional arrays work (foreach ($a as $k =>list ($b ,$c ));)
  • Type-hinted return values (syntax not yet solidified)
  • Hardened PHP patch will be added for increased security.

We"ll continue to eagerly monitor PHP6"s progress!

Updated on: 2009-11-10

Posted on: 2009-04-28

PHP 5.3 release candidate 1 was released a few days ago. The final version is expected to be released in the upcoming weeks.

This article presents an interview with core PHP developer Lukas Kahwe Smith that has pushed many of the new features of PHP 5.3 as release manager.

Lukas talks about PHP 5.3 new features such as lambda functions, closures and PHAR support. He also explains what are traits, which for now it is a feature that was left out of PHP 5.3.

He also talks about future PHP 5.x and PHP 6, as well how anybody can help in the development of PHP to make it come out faster.



Contents

* Who is Lukas Kahwe Smith?
* Wiki at php.net
* PHP 5.3 features overview


* Future PHP 5.x versions
* What are traits?
* PHP 5.x versus PHP 6
* PHP 6 release
* PHP 6 adoption
* Helping in PHP development
* Conclusion

LKS = Lukas Kahwe Smith
PC = PHPClasses (Manuel Lemos)

PC: Lukas, can you please tell a bit about yourself, where do you come from, where do you work, and what has been you participation in the PHP group?

LKS: My name is Lukas Kahwe Smith. I have an east German mother, an Iranian father and an American stepfather. So there is a bit of almost everything in me. To complete things my step sister is Jewish. Well far east is still missing.

I started a company with a few friends from high school using PHP and MySQL. I think in 2002 or 2003 we went to Frankfurt for the international PHP conference. This was really my step into becoming part of the open source community and not "just" a user.

We actually met you (Manuel Lemos) there and based on your recommendation, the PEAR community suggested that I work on a merge of PEAR::DB and Metabase. After that I became quite involved in PEAR.

Slowly I shifted my interest towards PHP internals as due to work standards I was using less and less PEAR stuff. I started maintaining a wiki of all the open to do tasks, which has now spawned the creation of the official wiki site.

In the summer of 2008 I was then asked to join Johannes as release manager to help out with the organizational aspects.

I sometimes pride myself in being the only non-C coder that has php-src karma. :)

By the way, the PHP Group is actually a small number of people that are sort of the legal entity behind PHP. As such I am not a member of that group. I usually refer to the people working on PHP as the php.net crowd.

* Wiki at php.net

PC: Nice. Can you talk a bit more about that wiki in php.net? What is its purpose? Who should participate in it? How can an interested member of the PHP community get the necessary permissions to participate?

LKS: The purpose if the wiki is to improve the collaboration. So for example we use it for the to do lists for the various active branches. We also use it as a "scratchpad" to note things that need to be added to the manual.

The various teams inside PHP.net are also using it to note processes. Like there are pages that explain how to build PHP on windows.

The biggest thing that came out of the wiki is that people started writing RFCs when they were pitching bigger (and even some smaller) changes.

This makes it much easier for people (core developer and end users alike) to follow what is going on without getting those fairly useless "check the archives" replies. Now they can be pointed to the RFCs to see why something was done the way it was done, or why something was rejected.

One of the big concerns with the wiki is that people would use it as a replacement for adding things into the actual end manual and its something we have to constantly look out for.

The other concern was that content would quickly become unmanageable. As a result we only have people with a CVS account to any PHP.net project write access.

Everybody else can read everything and, of course, request an account. We will then ask the purpose and give access rights. So far all changes people wanted to see happen were either done by granting them access or someone else taking care of this. We are quite liberal here.

* PHP 5.3 features overview

PC: PHP 5.3 is about to be released. Can you give a quick overview of the most important features introduced by this release?

LKS: The biggest and most controversial one is obviously name spaces. We are aware that several people object to our choice of the separator but unfortunately we were unable to find a better alternative.

Other than that a lot of under the hood changes will give people a considerable speed boost, especially if they are not using a byte code cache.

Furthermore we added lambda functions and closures, as well as added some constructs to make working with static methods more powerful.

We also added several extensions of which I especially see PHAR being of huge importance, as it might define the way we package applications in the future.

* Performance versus memory usage

PC: Regarding performance, historically it seems that many performance improvements were made at the expense of greater run time memory usage. Do you agree? Can we expect noticeable increase in memory usage of PHP scripts as consequence of optimizations done on PHP 5.3?

LKS: I am not really an expert, since I do not know the PHP internals. There are some optimizations in PHP that should reduce memory overhead. Constants are now marked as constant internally. I guess in the past they were handled like normal variables, with simply no way in user-land to modify them. I am not sure how much of a difference this will make.

For people running into issue with memory consumption there is now a tool to get a better handle on this. PHP has trouble automatically freeing the memory when you do cyclic references:

$a = new Foo();
$b = new Bar();
$a->bar = $b;
$b->foo = $a;

In large complex scripts constructs like this happen more often that one would expect. Thanks to GSOC 2007 we now have a tool to collect memory when $a and $b are unset.

This does add some memory overhead to track all of the necessary information. However the benefit is that you can either automatically have PHP trigger or manually trigger a process that looks for cyclic references that can be freed up. With a bit of CPU work, this can mark a world of difference for large or long running scripts.

* Lambda functions, closures and PHAR

PC: Can you give a little more detail about what are lambda functions, closures and PHAR and what that is good for, to clarify those that never heard of those features before?

LKS: Lambda functions and closures really are great when working with one of the many internal functions that use callback functions.

Now, instead of polluting your name space with functions you will only call once and thereby risking a fatal error when you have overlapping function names, you can now create an anonymous one shot function on the fly.

PHAR is the result of a "proof of concept" PEAR package called "PHP_Archive".

It allows you to run an archive of several files just like you would be able to run a classic PHP application. So essentially you can take your application, tar it up and have your customers drop this in without having to extract the archive contents.

PHP can read this archive very efficiently. Even byte code caches can handle PHARs. The performance is really good, in some cases due to reduced disk I/O it can even be faster, but I have not checked the latest benchmarks in a while. I think its clear that this reduces a lot of the code maintenance nightmares.

* Future PHP 5.x versions

PC: What features do you expect or wish to be available future PHP 5.x versions?

LKS: Well, I am really unhappy that we did not manage to include traits into PHP 5.3. But something we had to give up, as we were struggling with getting 5.3 out the door because we already had so many features that needed attention. That being said, I do not expect a PHP 5.4.

* What are traits?

PC: Can you elaborate on what are traits and what they are good for in a typical PHP project?

LKS: We do not have multiple inheritance in PHP. The closest we offer right now is being able to implement multiple interfaces. We felt that there is too much of a WTF? factor when two classes have conflicting method definitions.

Traits try to solve the issue differently. Essentially traits are like copy and paste, with a simple syntax to handle any arising conflicts explicitly, which hopefully gets rid of the WTF? factor.

So with a trait you can define and implement your methods in one place and then have those implementations be essentially "copied over" by PHP.

Sounds complex? Its actually quite a lot easier than I think I am making it sound here. Stefan Marr has written an updated RFC that explains everything (including the research behind this).

A possible use case is the classic "Active Record" problem. Forcing all your model classes to inherit from a common base class is really an ugly clutch, but currently there isn"t really a very efficient alternative.

With traits you would not have to do this, as you would simply use a trait for the storage related methods and import them into any model class.

* PHP 5.x versus PHP 6

PC: Andrei Zmievski is basically the architect of the main PHP 6 feature, which is the native Unicode support for representing text strings.

He was in Brazil last October in a great PHP event named CONAPHP - Congresso Nacional de PHP:

Andrei gave a talk named "PHP for Grownups - How 5.3, 6, and intl will change your life" on which he mentioned that PHP 6 is basically PHP 5.3 plus Unicode support.

Do you expect that any other improvements to PHP that will be pushed to PHP 6 rather than future PHP 5.x versions?

LKS: Right. This will remain true for the most part. Andrei is now back on making PHP 6.0 happen, since his new employer is able to give him the required time.

As such we have not made a final decision, but from the vibes I have been getting from most people I talked to on this topic, we might see a PHP 5.4 eventually if we find that the step from 5.3 to 6.0 will be a hindrance to the adoption of 6.0. Or in other words PHP 5.4 might come out after 6.0 is out to backport some features (for example traits). But first we need to figure out PHP 6.0.

* PHP 6 release

PC: Andrei mentioned that PHP 6 is expected to be released some time later in 2009. Do you have a more specific expectation for a release date?

LKS: Based on the experience with PHP 5.3, I would say it will be hard, but not impossible, to even make it in 2010.

* PHP 6 adoption

PC: I think PHP 5 suffered a long delay in adoption mostly due to backwards incompatible changes that would require existing code to be rewritten.

Often companies did not want to spend more money on rewriting code that just works in PHP 4. Do you agree? Do you think PHP 6 may also suffer of that problem? If so, do you expect it to be worse problem under PHP 6?

LKS: Not really. Of course backwards compatibility issues played a factor. PHP 4 was simply quite good. PHP 5 brought with its new features that needed a lot of education for the vast numbers of self taught PHP developers.

Most PHP developers do not have a computer science background, so they did not really understand the new potential of all the new OO features. So it took some time for people to start implementing frameworks and tools to make those new OO features usable for the great masses of developers.

As such PHP 6 will be in a different situation. It will for the most part "only" add Unicode support. While I am sure that many novice programmers struggle with encodings, it will be quickly evident for all users that do have to deal with non ASCII encodings, that its easier to use PHP 6.

The main challenge will be making sure that the performance will not suffer too much because of the obvious additional work that needs to be done behind the scenes to have an engine that is actually encoding aware.

* Helping in PHP development

PC: What can interested developers do to help to make PHP developments come out faster?

LKS: Write tests, write documentation, test our preview releases. For the first part I would suggest to join the test fest efforts, which is a global event that tries to encourage end users to participate in the efforts to write tests.

As for writing documentation we have also worked hard to reduce the barrier to entry. For one the process is now better documented and the tool chain is now entirely comprised of PHP .

For running tests, we just ask people to follow the news on the PHP php.net Web site.

PC: How can anybody contact you to get more information about PHP developments and how they can help?

LKS: What I suggest to subscribe to one of the many mailing lists and simply lurk a bit. Sooner rather than later an opportunity to jump in an help will come.

Also remember that talk is cheap, so I recommend to just try and do something. People who do things will find that there are plenty of people willing to steer them in the right direction. People that just talk have a tendency to just use up time in endless discussion.

Another approach is to hook up with one of the many physical or virtual user communities. Going to a conference to network, or better yet an unconference, which at a much lower price tend to encourage active participation and networking even more.

I can honestly say that joining PHP.net has made me a better programmer and has been my single most effective career building step. My employer also benefits from the huge network of people I know.

* Conclusion

PC: Lukas, thank you for this interview.

LKS: I appreciate your efforts to make PHP code more accessible and to enable people to share their code.

PC: As a side comment, I would like to mention that the PHPClasses blog system, which is custom tailored like everything else on the PHPClasses site, was recently enhanced to allow submission of articles written by any user of the site.

If you or anybody else would like to submit articles of general interest of the PHP community, feel free to do so by going to this page. The site has a reasonably large audience, so posting interesting PHP articles in the blog will give you great instant exposure to any issue that you feel is of the interest of the PHP developers.

LKS: OK, good to know. I might make use of this at times.

PC: Feel free to do it. Thank you.






Загрузка...