Skip to content

PHP 학습 php curl_setopt 이 함수

2009.03.31 10:24

디케 조회 수:19883

php curl_setopt 이 함수

하는 역할은 내가 원하는 주소의 페이지에서 내가 임의의 값을 넣고 그 넣은 값으로 페이지에서 리턴되는 값을 받아오는 역할입니다.


$ch = curl_init([String url])        /* curl 세션의 초기화 [파라메터는 선택사항]. */ 

curl_setopt($ch, OPTION, VALUE)  /* curl 옵션을 세팅한다. */ 

curl_setopt 의 OPTION 
      CURLOPT_HEADER    : 헤더 정보를 받기 원한다면 이 옵션을 추가한다. VALUE : 1 OR true 
      CURLOPT_NOBODY    : 본문의 정보를 받기 원하지 않는다면 이 옵션을 추가한다. 
      CURLOPT_TIMEOUT  : curl 타임아웃을 설정한다. 
      CURLOPT_URL            : 접속할 url정보를 설정 
      CURLOPT_REFERER  : 리퍼러 정보를 설정 
      CURLOPT_USERAGENT : 에이전트 정보를 설정 
      CURLOPT_POST          : 전송 메소드를 post로 정의한다. 
      CURLOPT_POSTFIELDS: POST 메소드라면 파라미터 값들을 이 옵션에 정의하면된다. 


curl_exec($ch)      /* curl을 실행 */ 

curl_errno($ch)    /* 에러번호를 가져온다. */ 

curl_error($ch)    /* 에러 메시지를 가져온다. */ 

curl_getinfo($ch)  /* 상태 정보를 리턴한다. */ 

curl_close($ch)  /* curl 세션을 닫는다 */ 

 curl을 이용한 Gmail 로그인 예제. 

$src = "https://".$gmailId.":".$gmailPw.""; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
curl_setopt ($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_POST,true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_USERAGENT, 'My Agent Name'); 
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); 
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); 

$res = curl_exec($ch); 


/** 결과는 Atom xml 형식이다. DOM 또는 xml 파싱 function을 이용해서 파싱하면 됩니다. **/ 
echo $res; 




curl_init()가 반환한 cURL 핸들입니다.


The CURLOPT_XXX option to set.


The value to be set on option .

value should be a bool for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_AUTOREFERERTRUE to automatically set the Referer: field in requests where it follows aLocation: redirect.Available since PHP 5.1.0.
CURLOPT_COOKIESESSIONTRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only.Available since PHP 5.1.0.
CURLOPT_CRLFTRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DNS_USE_GLOBAL_CACHETRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.
CURLOPT_FAILONERRORTRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_FILETIMETRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option withcurl_getinfo().
CURLOPT_FOLLOWLOCATIONTRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: "headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSETRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECTTRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRTTRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSEto disable EPRT and LPRT and use PORT only.Added in PHP 5.0.0.
CURLOPT_FTP_USE_EPSVTRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.
CURLOPT_FTPAPPENDTRUE to append to the remote file instead of overwriting it.
CURLOPT_FTPLISTONLYTRUE to only list the names of an FTP directory.
CURLOPT_HEADERTRUE to include the header in the output.
CURLOPT_HTTPGETTRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.
CURLOPT_HTTPPROXYTUNNELTRUE to tunnel through a given HTTP proxy.
CURLOPT_MUTETRUE to be completely silent with regards to the cURL functions.
CURLOPT_NETRCTRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.
CURLOPT_NOBODYTRUE to exclude the body from the output. Request method is then set to HEAD. Changing this to FALSE does not change it to GET.

TRUE to disable the progress meter for cURL transfers.

Note: PHP automatically sets this option to TRUE, this should only be changed for debugging purposes. 

CURLOPT_NOSIGNALTRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used.Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_POSTTRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_RETURNTRANSFERTRUE to return the transfer as a string of the return value of curl_exec()instead of outputting it out directly.
CURLOPT_SSL_VERIFYPEERFALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE ifCURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2).TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10.
CURLOPT_TRANSFERTEXTTRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.
CURLOPT_UNRESTRICTED_AUTHTRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed.Added in PHP 5.0.0.
CURLOPT_UPLOADTRUE to prepare for an upload.
CURLOPT_VERBOSETRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.

value should be an integer for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_BUFFERSIZEThe size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however.Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_CONNECTTIMEOUTThe number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely.
CURLOPT_DNS_CACHE_TIMEOUTThe number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.
CURLOPT_FTPSSLAUTHThe FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first),CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide).Added in cURL 7.12.2 and PHP 5.1.0.
CURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use),CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).


The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.



Added in PHP 5.0.0.
CURLOPT_INFILESIZEThe expected size, in bytes, of the file when uploading a file to a remote site.
CURLOPT_LOW_SPEED_LIMITThe transfer speed, in bytes per second, that the transfer should be below duringCURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort.
CURLOPT_LOW_SPEED_TIMEThe number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort.
CURLOPT_MAXCONNECTSThe maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.
CURLOPT_MAXREDIRSThe maximum amount of HTTP redirections to follow. Use this option alongsideCURLOPT_FOLLOWLOCATION.
CURLOPT_PORTAn alternative port number to connect to.

Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also CURLOPT_REDIR_PROTOCOLS.


Added in cURL 7.19.4 and PHP 5.2.10.
CURLOPT_PROXYAUTHThe HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, onlyCURLAUTH_BASIC and CURLAUTH_NTLM are currently supported.Added in cURL 7.10.7 and PHP 5.1.0.
CURLOPT_PROXYPORTThe port number of the proxy to connect to. This port number can also be set inCURLOPT_PROXY.Added in PHP 5.0.0.
CURLOPT_PROXYTYPEEither CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5 .Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_REDIR_PROTOCOLSBitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in a transfer that it follows to in a redirect when CURLOPT_FOLLOWLOCATION is enabled. This allows you to limit specific transfers to only be allowed to use a subset of protocols in redirections. By default libcurl will allow all protocols except for FILE and SCP. This is a difference compared to pre-7.19.4 versions which unconditionally would follow to all protocols supported. See also CURLOPT_PROTOCOLS for protocol constant values.Added in cURL 7.19.4 and PHP 5.2.10.
CURLOPT_RESUME_FROMThe offset, in bytes, to resume a transfer from.
CURLOPT_SSL_VERIFYHOST1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.
CURLOPT_SSLVERSIONThe SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually.
CURLOPT_TIMECONDITIONHow CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADERis TRUE. Use CURL_TIMECOND_IFUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default.Added in PHP 5.1.0.
CURLOPT_TIMEOUTThe maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEVALUEThe time in seconds since January 1st, 1970. The time will be used byCURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.

value should be a string for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_CAINFOThe name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATHA directory that holds multiple CA certificates. Use this option alongsideCURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIEThe contents of the "Set-Cookie: " header to be used in the HTTP request.
CURLOPT_COOKIEFILEThe name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.
CURLOPT_COOKIEJARThe name of a file to save all internal cookies to when the connection closes.

A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET""POST""CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Note: Don't do this without making sure the server supports the custom request method first. 

CURLOPT_EGDSOCKETLike CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.
CURLOPT_ENCODINGThe contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity""deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent.Added in cURL 7.10.
CURLOPT_FTPPORTThe value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACEThe name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KRB4LEVELThe KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear""safe""confidential""private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDSThe full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
CURLOPT_PROXYThe HTTP proxy to tunnel requests through.
CURLOPT_PROXYUSERPWDA username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILEA filename to be used to seed the random number generator for SSL.
CURLOPT_RANGERange(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERERThe contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SSL_CIPHER_LISTA list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERTThe name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWDThe password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPEThe format of the certificate. Supported formats are "PEM" (default), "DER", and"ENG".Added in cURL 7.9.3 and PHP 5.0.0.
CURLOPT_SSLENGINEThe identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULTThe identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEYThe name of a file containing a private SSL key.

The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

Note: Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe. 

CURLOPT_SSLKEYTYPEThe key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".
CURLOPT_URLThe URL to fetch. This can also be set when initializing a session with curl_init().
CURLOPT_USERAGENTThe contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERPWDA username and password formatted as "[username]:[password]" to use for the connection.

value should be an array for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_HTTP200ALIASESAn array of HTTP 200 responses that will be treated as valid responses and not as errors.Added in cURL 7.10.3 and PHP 5.0.0.
CURLOPT_HTTPHEADERAn array of HTTP header fields to set.
CURLOPT_POSTQUOTEAn array of FTP commands to execute on the server after the FTP request has been performed.
CURLOPT_QUOTEAn array of FTP commands to execute on the server prior to the FTP request.

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_FILEThe file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_INFILEThe file that the transfer should be read from when uploading.
CURLOPT_STDERRAn alternative location to output errors to instead of STDERR.
CURLOPT_WRITEHEADERThe file that the header part of the transfer is written to.

value should be a string that is the name of a valid callback function for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_HEADERFUNCTIONThe name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written when using this callback function. Return the number of bytes written.
CURLOPT_PASSWDFUNCTIONThe name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_READFUNCTIONThe name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be read. The data must be read by using this callback function. Return the number of bytes read. Return 0 to signalEOF.
CURLOPT_WRITEFUNCTIONThe name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be written by using this callback function. Must return the exact number of bytes written or this will fail.


성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.