PHP Curl Function Library

Source: Internet
Author: User
Tags ftp commands http 200 http authentication http post ftp transfer ssl certificate sub domain


Using the PHP Curl Library, you can easily and effectively grab pages. Just run a script, then analyze the crawled pages, and then you can get the data you want in a program.
Whether you want to take part of the data from a link, or take an XML file and import it into the database, it's easy to get the Web content, CURL is a powerful PHP library
A forum login function that can impersonate a login but has not yet implemented a verification code enabled

You need to open the PHP.ini profile to enable the Extension=php_curl.dll library first
PHP Curl Library contains methods

curl_init-initialization of a curl session
curl_setopt-setting session parameters for a curl
curl_setopt_array-set session parameters as an array for a curl
Curl_exec-performing a Curl session
curl_close-closing a Curl session
curl_copy_handle-Copy all the contents and parameters of a Curl connection resource
curl_errno-returns a numeric number that contains the current session error information
curl_error-returns a string containing the current session error message
Curl_getinfo-gets the information for a Curl connection resource handle
curl_multi_add_handle-Adding a separate curl handle resource to a curl batch session
curl_multi_close-closing a batch handle resource
curl_multi_exec-parsing a Curl batch handle
curl_multi_getcontent-returns the text stream of the obtained output
Curl_multi_info_read-Gets the related transfer information for the currently resolved curl
curl_multi_init-initializing a curl batch handle resource
curl_multi_remove_handle-removing a handle resource from the Curl batch handle resource
Curl_multi_select-get all the sockets associated with the CURL extension, which can and be "selected"
curl_version-getting the version information about Curl

The Curl_init () function Initializes a curl session, and the only parameter to the Curl_init () function is optional, representing a URL address.
The function of the curl_exec () function is to perform a curl session, and the only argument is the handle returned by the Curl_init () function.
The function of the Curl_close () function is to close a curl session, and the only argument is the handle returned by the Curl_init () function.

Initialize a CURL Session object
$curl = Curl_init ();
The access path can be set directly when the object is created, or it can be set by later parameters
$curl = Curl_init (' Http://localhost/test/index2.php?testget=testGet ');

Set the URL to crawl
Curlopt_url: This is the URL address that you want to access and retrieve in PHP. You can also set this option when initializing with the Curl_init () function.
curl_setopt ($curl, Curlopt_url, ' http://localhost/test/index2.php?testget=testGet ');

Curlopt_header: If you want to include an HTTP header message in the output, set this option to a value other than 0. Default 0 is False
curl_setopt ($curl, Curlopt_header, 0);

Curlopt_returntransfer:1 If the request succeeds only returns the result, does not automatically output anything, 0 if successful only returns TRUE, automatically outputs the returned content. Default 0
curl_setopt ($curl, Curlopt_returntransfer, 1);

================================== using post to send messages and files
Send test information
$phoneNumber = ' 12345678910 ';
$message = ' This is message ';
$zhongWen = ' Test Chinese ';
Realpath () returns an absolute path, such as D:\ApacheServer\web\test\test.jpg
$file = Realpath (' test.jpg ');

The post information to be sent is concatenated into a string, in the following format. Phonenumber,message,zhongwen The key value that is received for post
$curlPostStr = ' phonenumber= '. $phoneNumber. ' &message= '. $message. ' &zhongwen= '. $zhongWen;
Or put the information in the array, in the following format. Phonenumber,message,zhongwen The key value that is received for post
' PhoneNumber ' = $phoneNumber,
' Message ' = $message,
' Zhongwen ' = $zhongWen,
' File ' = new Curlfile ($file)

Do not set Curlopt_post and curlopt_postfields default is get
Curlopt_post: If you want PHP to do a regular HTTP POST, set this option to a value other than 0. This post is an ordinary application/x-www-from-urlencoded type, most of which is used by HTML forms.
curl_setopt ($curl, Curlopt_post, 1);

Curlopt_postfields: A string that passes all the data as an HTTP POST.
Transferring information in a string is not a way to transfer files
curl_setopt ($curl, Curlopt_postfields, $CURLPOSTSTR);
PHP's curl supports generating multipart/form-data post requests by passing associative arrays (not strings) to Curlopt_postfields
curl_setopt ($curl, Curlopt_postfields, $CURLPOSTARR);

================================== using a proxy server
Proxy Server user name password, here is the simulation, not tested
$userName = "User";
$passWord = "PassWord";

Curlopt_httpproxytunnel:1 is enabled and is transmitted via an HTTP proxy when enabled. Default 0
curl_setopt ($curl, Curlopt_httpproxytunnel, 1);

Curlopt_proxy: Sets the HTTP proxy server through. Assume Proxy server address
curl_setopt ($curl, Curlopt_proxy, ' ');

CURLOPT_PROXYUSERPWD: The user name and password in the format "[Username]:[password]" that is connected to the proxy server.
curl_setopt ($curl, Curlopt_proxyuserpwd, "$userName: $passWord");

CURL's session can be set with a single parameter value by Curl_setopt, or a set of parameter values via Curl_setopt_array, in the following format
Sets an array of parameters
$options = Array (
Curlopt_url = ' Http://localhost/test/index2.php?testget=testGet ',
Curlopt_header = False
Set some parameter values for the session, using the new value that was set earlier
Curl_setopt_array ($curl, $options);

Run Curl, request a Web page
$data = curl_exec ($curl);

Close URL Request
Curl_close ($curl);

Show the data obtained
Var_dump ($data);
String ("world!") "Hello" Testget12345678910this is message test Chinese test.jpg "

The parameters that the CURL session can set are:
Curlopt_autoreferer automatically sets the Referer information in the header
Curlopt_binarytransfer gets the data back when Curlopt_returntransfer is enabled
When Curlopt_cookiesession is enabled, Curl simply passes a session cookie, ignoring other cookies, and by default, curl returns all cookies to the server. Session cookies are cookies that are used to determine if the session on the server is valid.
Curlopt_crlf converts a Unix newline character to a carriage return line break when enabled.
When Curlopt_dns_use_global_cache is enabled, a global DNS cache is enabled, which is thread-safe and is true by default.
Curlopt_failonerror Display HTTP status code, the default behavior is to ignore HTTP messages with numbers less than or equal to 400
When Curlopt_filetime is enabled, it attempts to modify the information in the remote document. The resulting information is returned through the curlinfo_filetime option of the Curl_getinfo () function.
When Curlopt_followlocation is enabled, "Location:" returned by the server server is returned to the server recursively in the header, using Curlopt_maxredirs to limit the number of recursive returns.
Curlopt_forbid_reuse Force disconnects after completing the interaction and cannot be reused.
Curlopt_fresh_connect forces a new connection to be taken in place of the connection in the cache.
When CURLOPT_FTP_USE_EPRT is enabled, the EPRT (or LPRT) command is used when FTP is downloaded. When set to False, disable EPRT and LPRT, use the port command only
When CURLOPT_FTP_USE_EPSV is enabled, the EPSV command is first tried before replying to PASV mode during FTP transfer. When set to False, the EPSV command is disabled.
Curlopt_ftpappend Append writes to the file instead of overwriting it when enabled.
Curlopt_ftpascii the alias of the Curlopt_transfertext.
Curlopt_ftplistonly only names of FTP directories are listed when enabled.
When Curlopt_header is enabled, the information for the header file is output as a data stream.
When Curlopt_httpget is enabled, the method for HTTP is set to get, because get is the default, so it is used only if it is modified.
Curlopt_httpproxytunnel is transmitted through an HTTP proxy when it is enabled.
Curlopt_mute all the modified parameters in the Curl function to restore the default values.
CURLOPT_NETRC After the connection is established, access the ~/.NETRC file to get the user name and password information to connect to the remote site.
Curlopt_nobody will not output the body part of HTML when it is enabled.
Curlopt_noprogress turn off the progress bar of the curl transfer when enabled, the default setting for this entry is true
Curlopt_nosignal when enabled, ignores all the signals that curl passes to PHP. This entry is turned on by default when SAPI multi-threaded transmissions.
When Curlopt_post is enabled, a regular POST request is sent with the type: application/x-www-form-urlencoded, just as the form commits.
Curlopt_put allow HTTP to send files when enabled, both Curlopt_infile and curlopt_infilesize must be set
Curlopt_returntransfer curl_exec () The information obtained is returned as a file stream, rather than as a direct output.
When Curlopt_ssl_verifypeer is disabled, curl terminates the validation from the service side. Use the Curlopt_cainfo option to set the certificate using the Curlopt_capath option to set the certificate directory if Curlopt_ssl_verifypeer (the default value is 2) is enabled, Curlopt_ssl_ Verifyhost needs to be set to true otherwise set to False. The default is true from Curl 7.10. The default binding installation starts with Curl 7.10.
Curlopt_transfertext uses ASCII mode for FTP transmissions when enabled. For LDAP, it retrieves plain text information rather than HTML. On Windows systems, the system does not set stdout to binary mode.
Curlopt_unrestricted_auth continuously appends user name and password information to multiple locations in the header generated by curlopt_followlocation, even if the domain name has changed.
Allow file transfer when Curlopt_upload is enabled
All information is reported when Curlopt_verbose is enabled and stored in stderr or specified curlopt_stderr
Curlopt_buffersize reads the size of the cache each time it gets data, this value is filled every time.
Curlopt_closepolicy is not curlclosepolicy_least_recently_used is curlclosepolicy_oldest, there are three other, but Curl temporarily does not support.
Curlopt_connecttimeout the time to wait before initiating the connection and, if set to 0, does not wait.
Curlopt_dns_cache_timeout sets the time to save DNS information in memory by default of 120 seconds.
Curlopt_ftpsslauth FTP authentication method: Curlftpauth_ssl (try SSL first), Curlftpauth_tls (try TLS first) or curlftpauth_default (let curl decide automatically). Added in Curl 7.12.2.
Curlopt_http_version set Curl to use the HTTP protocol, Curl_http_version_none (let CURL himself judge), Curl_http_version_1_0 (http/1.0), Curl_ Http_version_1_1 (http/1.1)
Curlopt_httpauth the HTTP authentication method used, the optional values are: Curlauth_basic,curlauth_digest,curlauth_gssnegotiate,curlauth_ntlm,curlauth_ Any,curlauth_anysafe, you can use the "|" operator to separate multiple values, curl allows the server to select one of the best supported values, Curlauth_any equivalent to Curlauth_basic | Curlauth_digest | Curlauth_gssnegotiate | Curlauth_ntlm,curlauth_anysafe equivalent to Curlauth_digest | Curlauth_gssnegotiate | Curlauth_ntlm
Curlopt_infilesize setting the size of the upload file
Curlopt_low_speed_limit when the transfer speed is less than Curlopt_low_speed_limit, PHP determines whether the transmission is canceled because it is too slow, depending on the curlopt_low_speed_time.
Curlopt_low_speed_time when the transfer speed is less than Curlopt_low_speed_limit, PHP determines whether the transmission is canceled because it is too slow, depending on the curlopt_low_speed_time.
Curlopt_maxconnects the maximum number of connections allowed, more than is the curlopt_closepolicy to decide which connections should be stopped
CURLOPT_MAXREDIRS Specifies the maximum number of HTTP redirects, and this option is used with curlopt_followlocation.
Curlopt_port an optional amount to specify the connection port
Curlopt_proxyauth authentication method for HTTP proxy connections. Use the bit field flags in Curlopt_httpauth to set the appropriate options. For proxy authentication only Curlauth_basic and CURLAUTH_NTLM are currently supported. Added in Curl 7.10.7.
Curlopt_proxyport the port of the proxy server. The port can also be set in Curlopt_proxy.
Curlopt_proxytype is not curlproxy_http (the default) is CURLPROXY_SOCKS5. was added in Curl 7.10.
Curlopt_resume_from a byte offset (used to resume a breakpoint) when the transfer is resumed
Curlopt_ssl_verifyhost 1 Checks If there is a common name (common name) in the server SSL certificate. Note: The common name (Common name) is generally filled in with the domain name (domain) or subdomain (sub domain) where you will be applying for an SSL certificate. 2 checks if the common name exists and matches the host name provided.
The SSL version (2 or 3) used by the curlopt_sslversion. By default, PHP detects this value by itself, although in some cases it needs to be set manually.
Curlopt_timecondition if edited after a certain time specified by Curlopt_timevalue, use Curl_timecond_ifmodsince to return to the page if it has not been modified and Curlopt_ Header is true, returns a header,curlopt_header of "304 not Modified" to false, using Curl_timecond_isunmodsince, the default value is Curl_timecond_ Ifmodsince
Curlopt_timeout set the maximum number of seconds that curl allows to execute
Curlopt_timevalue sets the timestamp used by a curlopt_timecondition, which is used by default in Curl_timecond_ifmodsince
Curlopt_cainfo a file name that holds 1 or more certificates used to authenticate the server. This parameter is only meaningful when used with Curlopt_ssl_verifypeer.
Curlopt_capath A directory that holds multiple CA certificates. This option is used in conjunction with Curlopt_ssl_verifypeer.
Curlopt_cookie set the contents of the "Set-cookie:" section of the HTTP request.
Curlopt_cookiefile contains the file name of the cookie information, which can be Netscape format or HTTP style header information.
Curlopt_cookiejar the name of the file that holds the cookie information after the connection is closed
Curlopt_customrequest uses a custom request message instead of "GET" or "HEAD" as an HTTP request. This is for executing "DELETE" or other more covert HTTP requests. Valid values such as "GET", "POST", "CONNECT" and so on. In other words, do not enter the entire HTTP request here. For example, entering "get/index.html http/1.0\r\n\r\n" is incorrect. Do not use before you determine the method that the server supports for this custom request.
Curlopt_egbsocket like Curlopt_random_file, except a filename to an Entropy gathering Daemon socket.
Curlopt_encoding header in the "Accept-encoding:" section of the content, the supported encoding format is: "Identity", "deflate", "gzip". If set to an empty string, it means that all encoding formats are supported
Curlopt_ftpport This value will be used to obtain the IP address required for the FTP "POST" instruction. The "POST" command tells the remote server to connect to the IP address we specify. This string can be a plain text IP address, host name, a network interface name (under Unix), or just a '-' to use the default IP address.
Curlopt_interface the name used in the external network interface, which can be an interface name, IP, or host name.
Curlopt_krb4level KRB4 (Kerberos 4) Security level setting, can be one of several values: "Clear", "safe", "confidential", "private". The default value is "Private", which is set to NULL when KRB4 is disabled, and now KRB4 security can only be used in FTP transport.
Curlopt_postfields the "POST" operation in HTTP. If you want to transfer a file you need to set a key value for the corresponding element value to new Curlfile (Realpath ($file)) $file to transfer the file corresponding to the relative path of the project
Curlopt_proxy Setting the HTTP proxy server through
Curlopt_proxyuserpwd the user name and password in the format "[Username]:[password]" that is connected to the proxy server.
Curlopt_random_file set the file name of the random number seed used to store SSL
Curlopt_range set the HTTP transmission range, you can set a transmission interval in the form of "X-y", if there are multiple HTTP transmissions, use commas to separate multiple values, such as: "X-y,n-m".
Curlopt_referer sets the value of the "REFERER:" section in the header.
Curlopt_ssl_cipher_list a list of SSL encryption algorithms. For example, Rc4-sha and TLSV1 are available encrypted lists.
Curlopt_sslcert passes a string containing a certificate in PEM format.
CURLOPT_SSLCERTPASSWD passes a password that contains the required use of the Curlopt_sslcert certificate.
The type of the Curlopt_sslcerttype certificate. The supported formats are "PEM" (the default), "DER" and "ENG".
Curlopt_sslengine the cryptographic engine variable used to specify the SSL private key in the Curlopt_sslkey.
Curlopt_sslengine_default variables used for asymmetric cryptographic operations.
Curlopt_sslkey The file name that contains the SSL private key.
CURLOPT_SSLKEYPASSWD the password for the SSL private key specified in Curlopt_sslkey. Since this option contains sensitive password information, remember to keep this PHP script secure.
Curlopt_sslkeytype the encryption type of the private key as specified in the Curlopt_sslkey, the supported key types are "PEM" (the default), "DER", and "ENG".
Curlopt_url need to get the URL address, can also be set in the PHP Curl_init () function.
Curlopt_useragent A string that contains a "user-agent" header in an HTTP request.
Curlopt_userpwd passes the user name and password required in a connection in the format: "[Username]:[password]".
The curlopt_http200aliases setting no longer handles HTTP 200 responses in the form of an error, in the format of an array.
Curlopt_httpheader sets an array of contents to be transferred in a header.
Curlopt_postquote a set of FTP commands executed on the server after the FTP request execution is complete.
Curlopt_quote a set of FTP commands that are executed on the server prior to FTP requests.
Curlopt_file sets the location of the output file, the value is a resource type, and the default is stdout (browser).
Curlopt_infile the file address to be read when uploading the file, the value is a resource type.
Curlopt_stderr sets an error output address, and the value is a resource type that supersedes the default STDERR.
Curlopt_writeheader sets the file address to write the header portion of the content, and the value is a resource type.
Curlopt_headerfunction sets a callback function that has two parameters, the first is the resource handle for curl, and the second is the header data for the output. The output of the header data must rely on this function to return the size of the data that has been written.
Curlopt_passwdfunction sets a callback function with three parameters, the first is the resource handle for curl, the second is a password prompt, and the third parameter is the maximum allowable password length. Returns the value of the password.
Curlopt_readfunction sets a callback function with two parameters, the first is the resource handle for curl, and the second is the data to be read. Data reads must depend on this function. Returns the size of the read data, such as 0 or EOF.
Curlopt_writefunction sets a callback function with two parameters, the first is the resource handle for curl, and the second is the data to be written. Data writes must depend on this function. Returns the exact size of the written data


Hello world!<?phpif ($_get[' Testget ') {    echo $_get[' Testget '];} if ($_post[' PhoneNumber ') {    echo $_post[' PhoneNumber '];} if ($_post[' message ']) {    echo $_post[' message '];} if ($_post[' Zhongwen ') {    echo $_post[' Zhongwen '];} if ($_files["file"]) {    echo $_files["file" [' Name '];}? >


PHP Curl Function Library

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.