반응형
PHP에서 cURL을 사용하여 응답을 얻는 방법
cURL을 통해 API를 호출하여 응답을 받는 함수를 원하는 독립형 PHP 클래스를 원합니다.누가 나 좀 도와줄래?
감사해요.
아래의 코드를 사용하여 안심할 수 있는 웹 서비스 URL에서 답변을 얻을 수 있습니다.소셜 멘션 URL을 사용합니다.
$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
솔루션의 핵심은 설정입니다.
CURLOPT_RETURNTRANSFER => true
그리고나서
$response = curl_exec($ch);
CURLOPT_RETURN TRANSFER는 응답을 페이지에 인쇄하는 대신 변수에 저장하도록 PHP에 지시합니다.그러면 $response에 응답이 포함됩니다.가장 기본적인 작업 코드는 다음과 같습니다(테스트하지 않은 것 같습니다).
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
다른 사람이 이 문제를 발견하면 응답 코드 또는 "응답"에 필요한 기타 정보를 제공하기 위해 다른 답변을 추가합니다.
http://php.net/manual/en/function.curl-getinfo.php
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
// also get the error and response code
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($errors);
var_dump($response);
출력:
string(0) ""
int(200)
// change www.google.com to www.googlebofus.co
string(42) "Could not resolve host: www.googlebofus.co"
int(0)
궁극의 curl php 기능:
function getURL($url,$fields=null,$method=null,$file=null){
// author = Ighor Toth <igtoth@gmail.com>
// required:
// url = include http or https
// optionals:
// fields = must be array (e.g.: 'field1' => $field1, ...)
// method = "GET", "POST"
// file = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
// please crete 'cookies' dir to store local cookies if neeeded
// do not modify below
$useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
$timeout= 240;
$dir = dirname(__FILE__);
$_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
$cookie_file = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
if($file!=null){
if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
die("curl setopt bit the dust: " . curl_error($ch));
}
//curl_setopt($ch, CURLOPT_FILE, $file);
$timeout= 3600;
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
if($fields!=null){
$postvars = http_build_query($fields); // build the urlencoded data
if($method=="POST"){
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
}
if($method=="GET"){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$url = $url.'?'.$postvars;
}
}
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
if (!$content){
$error = curl_error($ch);
$info = curl_getinfo($ch);
die("cURL request failed, error = {$error}; info = " . print_r($info, true));
}
if(curl_errno($ch)){
echo 'error:' . curl_error($ch);
} else {
return $content;
}
curl_close($ch);
}
이 간단한 것을 사용하고 있다
" " 클래스 연결 {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);
언급URL : https://stackoverflow.com/questions/6516902/how-to-get-response-using-curl-in-php
반응형
'itsource' 카테고리의 다른 글
foreach 루프의 값을 배열에 저장하려면 어떻게 해야 합니까? (0) | 2022.11.04 |
---|---|
관찰 가능한 rxJava2와 플로우 가능한 rxJava2 (0) | 2022.11.04 |
푸른색 클라우드 제공자에 개인 링크를 생성하려고 할 때 발생하는 문제 (0) | 2022.11.04 |
MacOS에서 MariaDB 10.4의 루트 비밀번호를 설정하는 방법 (0) | 2022.11.04 |
log4j.properties 파일에서 log4j.rootLogger 속성의 중요성은 무엇입니까?이 부동산을 사용하지 않으면 어떻게 됩니까? (0) | 2022.11.04 |