This repository has been archived by the owner on Oct 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FakeSSR.php
60 lines (54 loc) · 1.64 KB
/
FakeSSR.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
<?php
namespace byn9826\FakeSSR;
use Jaybizzle\CrawlerDetect\CrawlerDetect;
class FakeSSR {
public static function detect($cache_path = null, $expire = false) {
$CrawlerDetect = new CrawlerDetect;
if($CrawlerDetect->isCrawler()) {
$html = self::render($expire, $cache_path);
echo $html;
exit;
}
}
private static function render($expire, $cache_path) {
$address = isset($_SERVER['HTTPS']) ? "https" : "http";
$address .= '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ($expire === 0) {
return self::crawl($expire, null, $address);
} else if ($expire !== 0) {
$file_path = $cache_path . '/__' . str_replace('/', '', $address) . '__.html';
return self::check($file_path, $expire) ?
file_get_contents($file_path) : self::crawl($expire, $file_path, $address);
}
}
public static function check($file_path, $expire) {
if (!file_exists($file_path)) {
return false;
}
if (!$expire) {
return true;
}
return time() < filemtime($file_path) + $expire * 60;
}
public static function crawl($expire, $file_path, $address) {
$cmd = 'google-chrome --headless --disable-gpu --dump-dom --no-sandbox --window-size=1280,1696 ';
$cmd .= $address . '; echo $?';
$content = shell_exec($cmd);
$content = substr($content, 0, -2);
$dom = new \DOMDocument();
$dom->loadHTML($content);
$script = $dom->getElementsByTagName('script');
$remove = [];
foreach ($script as $item) {
$remove[] = $item;
}
foreach ($remove as $item) {
$item->parentNode->removeChild($item);
}
$html = $dom->saveHTML();
if ($expire !== 0) {
$result = file_put_contents($file_path, $html);
}
return $html;
}
}