Skip to content

Commit 08ccdd9

Browse files
authored
Add timeout to remaining HTTP requests (#316)
Prevent get_headers() and file_get_contents() from hanging indefinitely. Changes: - Utility::urlExists() fallback: Add stream context with 5s timeout - Utility::getHeaderFromUrl(): Add 5s timeout to stream context defaults - Mime::getMimeTypeByUrl(): Add stream context with 5s timeout - Message::_readFile(): Add 10s timeout (files may be larger)
1 parent c297d8e commit 08ccdd9

3 files changed

Lines changed: 19 additions & 5 deletions

File tree

src/Mailer/Message.php

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -398,9 +398,12 @@ protected function _getMime($filename, $default = 'application/octet-stream') {
398398
* @return string File contents in base64 encoding
399399
*/
400400
protected function _readFile($path) {
401-
$context = stream_context_create(
402-
['http' => ['header' => 'Connection: close']],
403-
);
401+
$context = stream_context_create([
402+
'http' => [
403+
'timeout' => 10,
404+
'header' => 'Connection: close',
405+
],
406+
]);
404407
$content = file_get_contents($path, false, $context);
405408
if (!$content) {
406409
throw new RuntimeException('No content found for ' . $path);

src/Utility/Mime.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -794,8 +794,13 @@ public static function _detectMimeType($file) {
794794
// Treat non local files differently
795795
$pattern = '~^https?://~i';
796796
if (preg_match($pattern, $file)) {
797+
$context = stream_context_create([
798+
'http' => [
799+
'timeout' => 5,
800+
],
801+
]);
797802
// phpcs:disable
798-
$headers = @get_headers($file);
803+
$headers = @get_headers($file, false, $context);
799804
// phpcs:enable
800805
if (!$headers || !preg_match("|\b200\b|", $headers[0])) {
801806
return '';

src/Utility/Utility.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,8 +307,13 @@ public static function urlExists($url, array $statusCodes = []): bool {
307307
return in_array($statusCode, $statusCodes, true);
308308
}
309309

310+
$context = stream_context_create([
311+
'http' => [
312+
'timeout' => 5,
313+
],
314+
]);
310315
// phpcs:disable
311-
$headers = @get_headers($url);
316+
$headers = @get_headers($url, false, $context);
312317
// phpcs:enable
313318
if ($headers && preg_match('|\b200\b|', $headers[0])) {
314319
return true;
@@ -346,6 +351,7 @@ public static function getHeaderFromUrl(string $url) {
346351

347352
$defaults = [
348353
'http' => [
354+
'timeout' => 5,
349355
'header' => "Accept: text/html\r\n"
350356
. "Connection: Close\r\n"
351357
. "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",

0 commit comments

Comments
 (0)