| 365 |
lars |
1 |
<?php declare(strict_types=1);
|
|
|
2 |
namespace PHPHtmlParser;
|
|
|
3 |
|
|
|
4 |
use PHPHtmlParser\Exceptions\CurlException;
|
|
|
5 |
|
|
|
6 |
/**
|
|
|
7 |
* Class Curl
|
|
|
8 |
*
|
|
|
9 |
* @package PHPHtmlParser
|
|
|
10 |
*/
|
|
|
11 |
class Curl implements CurlInterface
|
|
|
12 |
{
|
|
|
13 |
|
|
|
14 |
/**
|
|
|
15 |
* A simple curl implementation to get the content of the url.
|
|
|
16 |
*
|
|
|
17 |
* @param string $url
|
|
|
18 |
* @param array $options
|
|
|
19 |
* @return string
|
|
|
20 |
* @throws CurlException
|
|
|
21 |
*/
|
|
|
22 |
public function get(string $url, array $options): string
|
|
|
23 |
{
|
|
|
24 |
$ch = curl_init($url);
|
|
|
25 |
if ($ch === false) {
|
|
|
26 |
throw new CurlException('Curl Init return `false`.');
|
|
|
27 |
}
|
|
|
28 |
|
|
|
29 |
if ( ! ini_get('open_basedir')) {
|
|
|
30 |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
if (isset($options['curlHeaders'])) {
|
|
|
34 |
curl_setopt($ch, CURLOPT_HTTPHEADER, $options['curlHeaders']);
|
|
|
35 |
}
|
|
|
36 |
|
|
|
37 |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
|
38 |
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
|
|
|
39 |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
|
|
40 |
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36');
|
|
|
41 |
curl_setopt($ch, CURLOPT_URL, $url);
|
|
|
42 |
|
|
|
43 |
$content = curl_exec($ch);
|
|
|
44 |
if ($content === false) {
|
|
|
45 |
// there was a problem
|
|
|
46 |
$error = curl_error($ch);
|
|
|
47 |
throw new CurlException('Error retrieving "'.$url.'" ('.$error.')');
|
|
|
48 |
} elseif ($content === true) {
|
|
|
49 |
throw new CurlException('Unexpected return value of content set to true.');
|
|
|
50 |
}
|
|
|
51 |
|
|
|
52 |
return $content;
|
|
|
53 |
}
|
|
|
54 |
}
|