PHP & Others

php curl 모든 사용법 (로그인 유지, 쿠키 설정, post 등)

페이지 정보

본문



https://blog.naver.com/reviewer__/221560841117


php curl 모든 사용법 (로그인 유지, 쿠키 설정, post 등)



1) 기본 사용법


기본적으로 호출된 url의 정보를 불러옵니다.


$url = "http://www.example.com"; //주소셋팅

$ch = curl_init(); //curl 로딩

curl_setopt($ch, CURLOPT_URL,$url); //curl에 url 셋팅

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 이 셋팅은 1로 고정하는 것이 정신건강에 좋음


$result = curl_exec ($ch); // curl 실행 및 결과값 저장

print_r($result); //출력

curl_close ($ch); // curl 종료


2) https로 호출시 다음이 기본 호출 방법입니다.


$url = "https://www.example.com"; //주소셋팅

$ch = curl_init(); //curl 로딩

curl_setopt($ch, CURLOPT_URL,$url); //curl에 url 셋팅

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 이 셋팅은 1로 고정하는 것이 정신건강에 좋음

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //true로 설정시 일부 https 사이트는 안 열림

curl_setopt($ch, CURLOPT_SSLVERSION,3); //ssl 셋팅


$result = curl_exec ($ch); // curl 실행 및 결과값 저장

print_r($result); //출력

curl_close ($ch); // curl 종료


3) respone(호출한 url)의 header 값이 필요하면 다음 옵션을 활성화시키면 됩니다.



근데 거의 쓸일 없음


curl_setopt($ch, CURLOPT_HEADER, 1 );



4) post 전송



get 전송은 url 셋팅하면 되는 거 아시죠?


$url = "https://www.example.com"; //주소셋팅

$postfields = 'id=sssss&password=123456'; //post값 셋팅 (id값과 password 값이 셋팅됨)


$ch = curl_init(); //curl 로딩

curl_setopt($ch, CURLOPT_URL,$url); //curl에 url 셋팅

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 이 셋팅은 1로 고정하는 것이 정신건강에 좋음

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 주소가 https가 아니라면 지울것

curl_setopt($ch, CURLOPT_SSLVERSION,3); // 주소가 https가 아니라면 지울것


curl_setopt($ch, CURLOPT_POST, 1); // 포스트 전송 활성화 

curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // curl에 포스트값 셋팅


$result = curl_exec ($ch); // curl 실행 및 결과값 저장

print_r($result); //출력

curl_close ($ch); // curl 종료



5) 쿠키 저장 및 가져오기



다음 옵션을 활성화시키면 됩니다. 


$filename = 'C:\example\http\static\cookie.txt'; // 윈도우에서는 절대주소 필요

$filename = './static/cookie.txt'; // 리눅스에서는 상대주소 사용하면됨


curl_setopt($ch, CURLOPT_COOKIEJAR, $filename); // 쿠키 값을 저장시킵니다.

쿠키 값을 불러내려면 다음 옵션을 활성화시키면 됩니다.


curl_setopt($ch, CURLOPT_COOKIEFILE, $filename); // 쿠키 값을 불러와 curl 실행시 같이 전송



6) 쿠키 값 직접 설정



일부 쿠키 값이 저장되지 않거나 필요할 때 다음 옵션을 사용합니다.


curl_setopt($ch, CURLOPT_COOKIE, 'name=value'); // 쿠키 값이 "추가됨"



7) referer 설정



일부 사이트의 경우 referer을 검증 값으로 사용할 수 있으니 셋팅 방법을 알아둡시다


curl_setopt($ch, CURLOPT_REFERER, 'https://example.com'); // https, http 구분하세요


8) curl로 로그인 및 로그인 유지


$url = "https://www.example.com/login "; //로그인 확인 주소

$postfields = 'id=sssss&password=123456'; //로그인 post 값

$filename = 'C:\example\http\static\cookie.txt'; // 윈도우에서는 절대주소 필요

$filename = './static/cookie.txt'; // 리눅스에서는 상대주소 사용하면됨


$ch = curl_init(); //curl 로딩

curl_setopt($ch, CURLOPT_URL,$url); //curl에 url 셋팅

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 이 셋팅은 1로 고정하는 것이 정신건강에 좋음

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 주소가 https가 아니라면 지울것

curl_setopt($ch, CURLOPT_SSLVERSION,3); // 주소가 https가 아니라면 지울것


curl_setopt($ch, CURLOPT_POST, 1); // 포스트 전송 활성화 

curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // curl에 포스트값 셋팅


curl_setopt($ch, CURLOPT_COOKIEJAR, $filename); // respone되는 쿠키값을 저장함


$result = curl_exec ($ch); // curl 실행 및 결과값 저장

print_r($result); //출력

curl_close ($ch); // curl 종료

이제 로그인 유지되었으니 홈페이지 내의 다른 url 을 호출할 수 있습니다.


이때 쿠키 값이 계속 변할 수 있으니 쿠키 값 저장은 항상 활성화하는 것은 팁입니다.


$url = "https://www.example.com/mypage "; //마이페이지 접속 주소

$filename = 'C:\example\http\static\cookie.txt'; // 윈도우에서는 절대주소 필요

$filename = './static/cookie.txt'; // 리눅스에서는 상대주소 사용하면됨


$ch = curl_init(); //curl 로딩

curl_setopt($ch, CURLOPT_URL,$url); //curl에 url 셋팅

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 이 셋팅은 1로 고정하는 것이 정신건강에 좋음

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 주소가 https가 아니라면 지울것

curl_setopt($ch, CURLOPT_SSLVERSION,3); // 주소가 https가 아니라면 지울것


curl_setopt($ch, CURLOPT_POST, 1); // 포스트 전송 활성화 

curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // curl에 포스트값 셋팅


curl_setopt($ch, CURLOPT_COOKIEJAR, $filename); // respone되는 쿠키값을 저장함

curl_setopt($ch, CURLOPT_COOKIEFILE, $filename); // 저장한 쿠키값을 불러옴


$result = curl_exec ($ch); // curl 실행 및 결과값 저장

print_r($result); //출력

curl_close ($ch); // curl 종료



9) 호출된 url의 자바스크립트를 무시하려면 다음 옵션을 사용하십시오


//location.href 같은 머리 아픈 옵션들을 가뿐히 버퍼 제어로 없앱니다 ^^

ob_start();

curl_exec ($ch);

ob_end_clean();

curl_close ($ch);



10) 파일 전송 또한 가능합니다.


//참고주소 https://stackoverflow.com/questions/3085990/post-a-file-string-using-curl-in-php

$delimiter_header = '----WebKitFormBoundary'.uniqid();

$delimiter = ''.$delimiter_header; // 사이트 규칙에 맞게 추가해주면됨. 잘모르면 빈칸 ㄱㄱ


// 파일 셋팅

$fileFields = array(

    'name' => array(

        'name' => '',

        'type' => 'application/octet-stream',

        'content' => ''), 

);


//일반 post 값 셋팅

$postFields = array(

    'id' => '1234'

);


$data = '';


// 여기서부터는 전송값들 정렬(셋팅)

// populate normal fields first (simpler)

foreach ($postFields as $name => $content) {

    $data .= $delimiter . "\r\n";

    $data .= 'Content-Disposition: form-data; name="' . $name . '"';

    // note: double endline

    $data .= "\r\n\r\n";

    $data .= $content;

    $data .= "\r\n";

}


// populate file fields

$data= '';

foreach ($fileFields as $name => $file) {

    $data .= $delimiter . "\r\n";

    // "filename" attribute is not essential; server-side scripts may use it

    $data .= 'Content-Disposition: form-data; name="' . $name . '";' .

        ' filename="'.$file['name'].'"' . "\r\n"; 

    // this is, again, informative only; good practice to include though

    $data .= 'Content-Type: ' . $file['type'] . "\r\n";

    // this endline must be here to indicate end of headers

    $data .= "\r\n";

    // the file itself (note: there's no encoding of any kind)

    $data .= $file['content'] . "\r\n";

}


$url = 'http://example.com/file_upload'; // 파일 업로드 주소

$ch = curl_init();


curl_setopt($ch, CURLOPT_HEADER, 1 );

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_HTTPHEADER , array('

    Content-Type: multipart/form-data; boundary=' . $delimiter_header,

    'Content-Length: ' . strlen($data)

    )); 

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_setopt($ch, CURLOPT_COOKIEJAR, $filename);

curl_setopt($ch, CURLOPT_COOKIEFILE, $filename);

curl_setopt($ch, CURLOPT_URL,"$url");


ob_start();

curl_exec ($ch);

ob_end_clean();

curl_close ($ch);






--------------------------------------


https://gogoke1.blog.me/20205463546


[php curl 쿠키 옵션 정보]


libcurl에 쿠키 엔진을 사용하고 인터페이스하는 여러 가지 방법을 제공합니다. 이 옵션은 기본 API에 의해 제공되는 것입니다. libcurl에 바인딩은 다른 방법을 사용하여에 대한 액세스를 제공 할 수 있습니다.


CURLOPT_COOKIE

서버에 보낼 쿠키 헤더의 정확한 내용을 지정하고자 할 때 사용된다.


CURLOPT_COOKIEFILE

쿠키 엔진을 활성화 libcurl에에게 해, 지정된 파일 쿠키의 초기 설정을 읽을 수 있습니다. 읽기 전용.


CURLOPT_COOKIEJAR

쿠키 엔진을 활성화 libcurl에 알려주기, 및 쉬운 핸들이 닫힐 때 지정된 cookiejar 파일에 알려진 모든 쿠키를 저장합니다. 쓰기 전용입니다.


CURLOPT_COOKIELIST

쿠키의 내부 저장 장치에 추가 할 단일 쿠키에 대한 자세한 정보를 제공합니다. 설정 한 모든 세부 HTTP 헤더로 쿠키를 전달, 또는 넷스케이프 쿠키 파일에서 줄을 전달합니다. 또한이 옵션 등 쿠키를 세척하는데 사용될 수있다


CURLINFO_COOKIELIST

링크리스트와 같은 내부 쿠키 저장소에서 쿠키 정보를 추출합니다.



---------------------------------


https://blog.naver.com/alzxcvbnm/221625744292


[curl 커맨드에 쿠키 적용]


curl -b cookie.txt -c cookie.txt abc.com


-b 옵션으로 서버로부터 온 쿠키 정보를 저장할 파일을 지정하며

-c 옵션으로 리퀘스트를 보낼 때 같이 보낼 쿠키를 가지고 있는 파일을 지정한다.



관련자료

등록된 댓글이 없습니다.
Today's proverb
참된 행복은 눈에 보이지 않는다. 참된 행복은 작지만 자기 일에 만족하고 자기 안에서 그것을 찾는 사람에게만 보이도록 가만 가만히 찾아온다.