Skip to content

Commit d13c431

Browse files
committed
Fix php-curl-class#521: Fix memory leak when class object unset, but not manually closed.
Move closure function outside class to avoid implicit reference to $this and allow __destruct() to be called as expected when a class instance is unset.
1 parent c3a5632 commit d13c431

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

src/Curl/Curl.php

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ public function __construct($base_url = null)
122122
$header_callback_data->rawResponseHeaders = '';
123123
$header_callback_data->responseCookies = array();
124124
$this->headerCallbackData = $header_callback_data;
125-
$this->setOpt(CURLOPT_HEADERFUNCTION, $this->createHeaderCallback($header_callback_data));
125+
$this->setOpt(CURLOPT_HEADERFUNCTION, createHeaderCallback($header_callback_data));
126126

127127
$this->setOpt(CURLOPT_RETURNTRANSFER, true);
128128
$this->headers = new CaseInsensitiveArray();
@@ -1302,25 +1302,6 @@ private function buildUrl($url, $mixed_data = '')
13021302
return $url . $query_string;
13031303
}
13041304

1305-
/**
1306-
* Create Header Callback
1307-
*
1308-
* @access private
1309-
* @param $header_callback_data
1310-
*
1311-
* @return callable
1312-
*/
1313-
private function createHeaderCallback($header_callback_data)
1314-
{
1315-
return function ($ch, $header) use ($header_callback_data) {
1316-
if (preg_match('/^Set-Cookie:\s*([^=]+)=([^;]+)/mi', $header, $cookie) === 1) {
1317-
$header_callback_data->responseCookies[$cookie[1]] = trim($cookie[2], " \n\r\t\0\x0B");
1318-
}
1319-
$header_callback_data->rawResponseHeaders .= $header;
1320-
return strlen($header);
1321-
};
1322-
}
1323-
13241305
/**
13251306
* Download Complete
13261307
*
@@ -1505,3 +1486,24 @@ private function setEncodedCookie($key, $value)
15051486
$this->cookies[implode('', $name_chars)] = implode('', $value_chars);
15061487
}
15071488
}
1489+
1490+
/**
1491+
* Create Header Callback
1492+
*
1493+
* Gather headers and parse cookies as response headers are received. Keep this function separate from the class so that
1494+
* unset($curl) automatically calls __destruct() as expected. Otherwise, manually calling $curl->close() will be
1495+
* necessary to prevent a memory leak.
1496+
*
1497+
* @param $header_callback_data
1498+
*
1499+
* @return callable
1500+
*/
1501+
function createHeaderCallback($header_callback_data) {
1502+
return function ($ch, $header) use ($header_callback_data) {
1503+
if (preg_match('/^Set-Cookie:\s*([^=]+)=([^;]+)/mi', $header, $cookie) === 1) {
1504+
$header_callback_data->responseCookies[$cookie[1]] = trim($cookie[2], " \n\r\t\0\x0B");
1505+
}
1506+
$header_callback_data->rawResponseHeaders .= $header;
1507+
return strlen($header);
1508+
};
1509+
}

0 commit comments

Comments
 (0)