Skip to content

Commit

Permalink
Helpers::fetchUrl() uses cURL if available because file_get_contents …
Browse files Browse the repository at this point in the history
…get stuck on some HTTPS sites.

For HTTPS download cacert.pem from https://curl.haxx.se/docs/caextract.html and add to the php.ini option 'curl.cainfo=c:\php\cacert.pem'
  • Loading branch information
dg committed Dec 1, 2016
1 parent f3ee4e3 commit 545e277
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
40 changes: 30 additions & 10 deletions src/Deployment/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,36 @@ public static function matchMask($path, array $patterns, $isDir = FALSE)
*/
public static function fetchUrl($url, & $error, array $postData = NULL)
{
$output = @file_get_contents($url, FALSE, stream_context_create([
'http' => $postData === NULL ? [] : [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($postData, NULL, '&'),
]
]));
$error = $output === FALSE
? preg_replace("#^file_get_contents\(.*?\): #", '', error_get_last()['message'])
: NULL;
if (extension_loaded('curl')) {
$ch = curl_init($url);
$options = [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
];
if ($postData !== NULL) {
$options[CURLOPT_POST] = TRUE;
$options[CURLOPT_POSTFIELDS] = $postData;
}
curl_setopt_array($ch, $options);
$output = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
} elseif (($code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) >= 400) {
$error = "responds with HTTP code $code";
}

} else {
$output = @file_get_contents($url, FALSE, stream_context_create([
'http' => $postData === NULL ? [] : [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($postData, NULL, '&'),
]
]));
$error = $output === FALSE
? preg_replace("#^file_get_contents\(.*?\): #", '', error_get_last()['message'])
: NULL;
}
return (string) $output;
}

Expand Down
6 changes: 5 additions & 1 deletion tests/Helpers.fetchUrl.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ Assert::contains('Example Domain', $output);
Assert::null($error);

$output = Helpers::fetchUrl('http://example.com/404', $error);
Assert::same('', $output);
if (extension_loaded('curl')) {
Assert::contains('Example Domain', $output);
} else {
Assert::same('', $output);
}
Assert::contains('404', $error);

0 comments on commit 545e277

Please sign in to comment.