반응형
PHPcurl 요청 예제
말을 많이 하지 않고, 직접 실례를 말하다
<?php
namespace rely\curl;
use rely\Facade;
use rely\Init;
/**
* Class Driver
* @package rely\curl
* @author Mr.taochuang <mr_taochuang@163.com>
* @date 2019/7/3 11:14
* curl 드라이브 클래스
*/
class Driver
{
/**
* @var object
* curl 개체
*/
private static $curl = null;
/**
* @var \rely\init\Config;
* setopt 설정 매개 변수
*/
private static $config;
private static $init = [
'timeout' => 60,
'verifyhost' => 0,
'sslcerttype' => 'PEM',
'sslkeytype' => 'PEM',
'verifypeer' => false
];
/**
* @var array
* 설정 setopt
*/
public static $setopt = [];
/**
* @var null
* 요청 url
*/
public static $url = null;
/**
* @var int
* 오류 코드
* 1 성공
* 2 요청 없음url
*/
public $code = 1;
/**
* @var string
*오류 메시지
*/
public $message = '';
/**
* @var
* 응답 상태
*/
private $status;
/**
* @var
* 응답 데이터
*/
private $response;
/**
* @var
* 처리 후 데이터
*/
private $data;
/**
*@var/ 네트워크 캐시
*/
public static $cache_curl;
/**
* Driver constructor.
* @param array $config
* curl 초기화
*/
public function __construct($config = [])
{
self::$curl = curl_init();
self::$config = (new \ReflectionClass(Facade::bind('config')))->newInstanceArgs([array_merge(self::$init, $config)]);
}
//여기서 사용하는 종류의 반사, 알고 싶은 대가는 아래 링크의 글을 보면 된다
/**
*@param null $url url 주소
* 등록 url 주소
*/
public function instance($url = null)
{
if (is_null($url)) {
$this->code = 2;
$this->message = 요청주소 http://xxxxxx 또는 https://xxxxxxxx'를 입력해주세요
} else {
self::$url = $url;
}
return $this;
}
/**
* @param array $param
* @return int
* get 요청
*/
public function get($param = [])
{
if (!empty($param)) self::$url .= (stripos(self::$url, '?') !== false ? '&' : '?') . http_build_query(Init::dataswitch()->toArray($param));
return self::request();
}
/**
* @param $param /요청 매개 변수
* @param $type /요청 유형 array json xml
* @return int
* 포스트 요청
*/
public function post($param, $type = 'array')
{
$dataswitch = Init::dataswitch();
if ($type == 'array') $param=http_build_query($dataswitch->toArray($param));
if ($type == 'json') $param=$dataswitch->toJson($param);
if ($type == 'xml') $param=$dataswitch->toXml($param);
self::setopt([CURLOPT_POST, true], [CURLOPT_POSTFIELDS, $param]);
return self::request();
}
/**
* @param $param /요청 매개 변수
* @return int
* 파일 요청
*/
public function file($param)
{
if (!is_array($param)) $param = Init::dataswitch()->toArray($param);
$build = true;
foreach ($param as $key => $value) if (is_object($value) && $value instanceof \CURLFile) {
$build = false;
} elseif (is_object($value) && isset($value->datatype) && $value->datatype === 'MY_CURL_FILE') {
$build = false;
$mycurl = new File((array)$value);
$param[$key] = $mycurl->get();
array_push(self::$cache_curl, $mycurl->tempname);
} elseif (is_string($value) && class_exists('CURLFile', false) && stripos($value, '@') === 0) {
if (($filename = realpath(trim($value, '@'))) && file_exists($filename)) {
$build = false;
$param[$key] = File::createCurlFile($filename);
}
}
self::setopt([CURLOPT_POST, true], [CURLOPT_POSTFIELDS, $build ? http_build_query($param) : $param]);
return self::request();
}
/**
* @return int
* 요청 보내기
*/
private function request()
{
self::setopt([CURLOPT_URL, !empty(self::$config->get('url')) ? self::$config->get('url') : self::$url],
[CURLOPT_TIMEOUT, self::$config->get('timeout')],
[CURLOPT_HEADER, false],
[CURLOPT_RETURNTRANSFER, true],
[CURLOPT_SSL_VERIFYPEER, self::$config->get('verifypeer')],
[CURLOPT_SSL_VERIFYHOST, self::$config->get('verifyhost')]);
foreach (self::$setopt as $maps) {
curl_setopt(self::$curl, $maps[0], $maps[1]);
}
list($this->response, $this->status) = [curl_exec(self::$curl), curl_getinfo(self::$curl)];
$this->data = (intval($this->status["http_code"]) === 200) ? $this->response : curl_errno(self::$curl);
curl_close(self::$curl);
return $this->data;
}
/**
* 에이전트 설정
* @param $Host /ip
* @param $Port /포트
*/
public function proxy($Host, $Port)
{
self::setopt([CURLOPT_PROXY, $Host], [CURLOPT_PROXYPORT, $Port]);
return $this;
}
/**
* ssl 설정 요청
* @param $ssl_cer
* @param $ssl_key
*/
public function ssl($ssl_cer, $ssl_key)
{
self::setopt([CURLOPT_SSLCERTTYPE, self::$config->get('sslcerttype')], [CURLOPT_SSLCERT, $ssl_cer], [CURLOPT_SSLKEYTYPE, self::$config->get('sslkeytype')], [CURLOPT_SSLKEY, $ssl_key]);
return $this;
}
/**
* HTTP 사용자 에이전트 헤더 설정
* @param $agent
* @return $this
*/
public function useragent($agent)
{
self::setopt([CURLOPT_USERAGENT, $agent]);
return $this;
}
/**
* setpot 설정
* curl 다중 매개 변수를 설정할 수 있습니다
* key=>value 대 패턴 디자인
* 예 useragent 방법
*/
public function setopt()
{
foreach (func_get_args() as $maps) {
self::$setopt[$maps[0]] = $maps;
}
}
}
PHP 체인 작업은 call과 callstatic 매직 방법을 통해 구현되며 phpstorm은 주석을 통해 function을 추적합니다
config 클래스 첨부
<?php
namespace rely\init;
/**
* Class Config
* @package rely\curl
* @author Mr.taochuang <mr_taochuang@163.com>
* @date 2019/7/3 11:25
* 설정 클래스
*/
class Config implements \ArrayAccess
{
/**
* @var array
*설정 정보
*/
private static $config = [];
/**
* @param $config
* 설정 초기화
*/
public function __construct($config=[])
{
self::$config = array_merge(self::$config, $config);
}
/**
* @param string|null $field
* @return array
* Config 설정 매개 변수 가져오기
*/
public static function get(string $field = null)
{
if (is_null($field)) return self::$config;
return isset(self::$config[$field]) ? self::$config[$field] : null;
}
/**
* @param string $field
* @param $value
* @return $this
* Config 매개 변수 설정
*/
public function set(string $field, $value)
{
self::$config[$field] = $value;
return $this;
}
/**
* @param string $field
* @return bool
* Config 설정의 존재 여부 판단
*/
public static function has(string $field):bool
{
return !is_null($this->get($field));
}
/**
* 설정 변수 설정
* @access public
* @param string $field 매개 변수 이름
* @param mixed $value 값
*/
public function __set(string $field, $value): void
{
$this->set($field, $value);
}
/**
* 설정 변수 가져오기
* @access public
* @param string $field 매개 변수 이름
* @return mixed
*/
public function __get(string $field)
{
return $this->get($field);
}
/**
* @param mixed $field
* @param mixed $value
* ArrayAccess
*/
public function offsetSet($field, $value): void
{
$this->set($field, $value);
}
public function offsetExists($field): bool
{
return $this->has($field);
}
public function offsetUnset($field)
{
throw new \Exception('not support: unset');
}
public function offsetGet($field)
{
return $this->get($field);
}
/**
* ArrayAccess
*/
}```
반응형
'개발 꿀팁 > PHP' 카테고리의 다른 글
PHP는 두 개의 타임스탬프가 같은 주에 있는지 어떻게 판단합니까? (0) | 2022.09.22 |
---|---|
php 타이머 phptimer (0) | 2022.09.22 |
phpredis의 추가 및 삭제 작업 라이브러리 (0) | 2022.09.21 |
php가 url을 해석하여 url의 매개 변수를 얻고, url 매개 변수를 얻는 네 가지 방식 (1) | 2022.09.21 |
PHP 추첨의 새로운 방법, 멀티채널 추첨 지원 (1) | 2022.09.20 |