-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUrlFetcher.php
99 lines (91 loc) · 2.64 KB
/
UrlFetcher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
/**
* This class serves 2 purposes.
* 1- some installs have a bugged openssl module,
* and file_get_contents fails on ssl pages due to it. so, curl is used to workaround it.
*
* 2-it can cache http requests. this is useful during development and
* testing, to reduce the time needed to test your changes.
*
* @author Chris Rehfeld
*/
class UrlFetcher
{
/**
* The directoy where the files will be cached. no trailing slash.
*/
const CACHE_DIR = './url_request_cache';
/**
* Retrieves the http response text for the given url. Optionally, try to satisy the request from the cache.
*
* This will always write to the cache.
*
* @param string $url
* @param boolean $useCached
* @return mixed string on success, or false on failure.
*/
public static function fetch($url, $useCached = false)
{
if ($useCached)
{
$data = self::getFromCache($url);
if (is_string($data))
{
return $data;
}
}
$data = self::request($url);
if (is_string($data))
{
self::putIntoCache($url, $data);
}
return $data;
}
/**
* Performs the http request.
*
* @param string $url
* @return mixed string on success, or false on failure.
*/
protected static function request($url)
{
//from http://stackoverflow.com/questions/14078182/openssl-file-get-contents-failed-to-enable-crypto
//use these setting because some ppl have buggy openssl module
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
return curl_exec($ch);
}
/**
* Gets cached data, if exists
* @param string $url
* @return string cached data or false
*/
protected static function getFromCache($url)
{
$file = self::filePath($url);
return is_readable($file) ? file_get_contents($file) : false;
}
/**
* Gets file path for a given url
* @param string $url
* @return string path to file
*/
protected static function filePath($url)
{
return self::CACHE_DIR . '/' . urlencode($url);
}
/**
* Caches data into file
* @param string $url
* @param string $data
*/
protected static function putIntoCache($url, $data)
{
file_put_contents(self::filePath($url), $data);
}
}