Index: main/streams/streams.c
===================================================================
--- main/streams/streams.c	(révision 290026)
+++ main/streams/streams.c	(copie de travail)
@@ -1858,22 +1858,11 @@
 			php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC,
 					"wrapper does not support stream open");
 		} else {
-			/* refcount++ to make sure the context doesn't get destroyed 
-			 * if open() fails and stream is closed */
-			if (context) {
-				zend_list_addref(context->rsrc_id);
-			}
 
 			stream = wrapper->wops->stream_opener(wrapper,
 				path_to_open, mode, options ^ REPORT_ERRORS,
 				opened_path, context STREAMS_REL_CC TSRMLS_CC);
 
-			/* if open() succeeded and context was not used, do refcount-- 
-			 * XXX if a wrapper didn't actually use context (no way to know that) 
-			 * and open() failed, refcount will stay increased */
-			if (context && stream && !stream->context) {
-				zend_list_delete(context->rsrc_id);
-			}
 		}
 
 		/* if the caller asked for a persistent stream but the wrapper did not
@@ -1974,7 +1963,18 @@
 PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context)
 {
 	php_stream_context *oldcontext = stream->context;
+
+	TSRMLS_FETCH();
+
 	stream->context = context;
+
+	if (context) {
+		zend_list_addref(context->rsrc_id);
+	}
+	if (oldcontext) {
+		zend_list_delete(oldcontext->rsrc_id);
+	}
+
 	return oldcontext;
 }
 
Index: main/streams/transports.c
===================================================================
--- main/streams/transports.c	(révision 290026)
+++ main/streams/transports.c	(copie de travail)
@@ -134,7 +134,7 @@
 			context STREAMS_REL_CC TSRMLS_CC);
 
 	if (stream) {
-		stream->context = context;
+		php_stream_context_set(stream, context);
 
 		if ((flags & STREAM_XPORT_SERVER) == 0) {
 			/* client */
