97 lines
2.8 KiB
PHP
97 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Libraries;
|
|
|
|
use GuzzleHttp\Cookie\CookieJar;
|
|
use GuzzleHttp\Client;
|
|
|
|
class MyWebLibrary extends CommonLibrary
|
|
{
|
|
private $_client = null;
|
|
private $_cookieJar = null;
|
|
private $_host = null;
|
|
|
|
public function __construct(string $host)
|
|
{
|
|
parent::__construct();
|
|
$this->_host = $host;
|
|
}
|
|
|
|
final protected function getHost(): string
|
|
{
|
|
return $this->_host;
|
|
}
|
|
final protected function getClient(): Client
|
|
{
|
|
if ($this->_client === null) {
|
|
$this->_client = new Client(['verify' => false]);
|
|
}
|
|
return $this->_client;
|
|
}
|
|
|
|
final protected function getCookieJar()
|
|
{
|
|
if ($this->_cookieJar === null) {
|
|
$this->_cookieJar = new CookieJar();
|
|
}
|
|
return $this->_cookieJar;
|
|
}
|
|
|
|
public function getContent(string $url, array $options = []): string
|
|
{
|
|
//url에 http 나 https가 포함되어 있지않으면
|
|
if (!($this->isContainsHttpOrHttps($url))) {
|
|
$url = $this->gethost() . $url;
|
|
}
|
|
$response = $this->getClient()->get($url, $options);
|
|
if ($response->getStatusCode() != 200) {
|
|
throw new \Exception("error", "{$url} 접속실패: " . $response->getStatusCode());
|
|
}
|
|
return $response->getBody()->getContents();
|
|
}
|
|
|
|
// 로그인 메서드
|
|
public function login($url, $username, $password): bool
|
|
{
|
|
$response = $this->getClient()->post($this->gethost() . $url, [
|
|
'form_params' => [
|
|
'username' => $username,
|
|
'password' => $password,
|
|
],
|
|
'cookies' => $this->getCookieJar(),
|
|
]);
|
|
if ($response->getStatusCode() == 200) {
|
|
log_message("notice", "로그인 성공");
|
|
if ($this->getDebug()) {
|
|
echo var_dump($response);
|
|
}
|
|
return true;
|
|
} {
|
|
log_message("error", "로그인 실패: " . $response->getStatusCode());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// 파일 다운로드 메서드
|
|
public function download(string $url): array
|
|
{
|
|
log_message("debug", "donwload:URL-> " . $url);
|
|
$fileNames = explode('/', $url);
|
|
if (!is_array($fileNames) || !count($fileNames)) {
|
|
throw new \Exception("Download URL Error:" . $url);
|
|
}
|
|
$fileName = array_pop($fileNames);
|
|
if (!$this->getDebug()) {
|
|
$content = $this->getContent($url, [
|
|
'cookies' => $this->getCookieJar(),
|
|
// 'sink' => $savePath,
|
|
]);
|
|
if (!$content) {
|
|
throw new \Exception("{$fileName} 파일 다운로드 실패");
|
|
}
|
|
log_message("notice", "{$fileName} 파일이 다운로드되었습니다!");
|
|
}
|
|
return array($fileName, $content);
|
|
}
|
|
}
|