How to implement GET and POST requests using CURL in PHP

Source: Internet
Author: User
Tags ftp commands asymmetric encryption
Using CURL in PHP to implement GET and POST requests and introducing cURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, cURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET. the best thing is that PHP also supports the cURL Library. PHP cURL library can be used to easily and effectively capture webpages. you only need to run a script, analyze the web page you crawled, and then you can get the data you want as a program. whether you want to retrieve part of the data from a link or an XML file and import it to the database, you may simply get the webpage content, cURL is a powerful PHP library. II. CURL function library. curl_close-close a curl session curl_copy_handle-copy all content and parameters of a curl connection resource curl_errno-returns a number containing the current session error message curl_error-returns a message containing the current session error message string curl_exec-execute a curl session curl_getinfo-get the information of a curl connection resource handle curl_init-initialize a curl session curl_multi_add_handle-add a separate curl handle resource curl_multi_close to the curl batch processing session-close A batch processing handle resource curl_multi_exec-parses a curl batch processing handle curl_multi_getcontent-returns the obtained output text stream curl_multi_info_read-obtains the transmission information of the currently resolved curl curl_multi_init-initializes a curl batch processing handle resource curl_multi_remove_handle-remove a handle resource in the curl batch processing handle curl_multi_select-Get all the sockets associated with the cURL extension, which can then be "selected" curl_setopt_array-set the session parameter curl_setopt for a curl in the form of an array-set the session parameter curl_version for a curl-get the curl-related version information curl_init () the function initializes a curl session. the unique parameter of the curl_init () function is optional, indicating a url address. the role of the curl_exec () function is to execute a curl session. the unique parameter is the handle returned by the curl_init () function. the function curl_close () is used to close a curl session. the only parameter is the handle returned by the curl_init () function. 3. basic steps for PHP to create a CURL request ①: initialize curl_init () ②: Set the attribute curl_setopt (). there is a long string of cURL parameters that can be set. they can specify the details of URL requests. ③: execute and obtain the result curl_exec () ④: release handle curl_close () IV. CURL implementation GET and POST ①: GET implementation Running result: image ②: POST implementation "Coder", "password" => "12345"); curl_setopt ($ curl, CURLOPT_POSTFIELDS, $ post_data); // run the command $ data = curl_exec ($ curl ); // Close the URL request curl_close ($ curl); // display the obtained data print_r ($ data);?> ③: If the obtained data is in json format, use the json_decode function to interpret it as an array. $ output_array = json_decode ($ output, true); if json_decode ($ output) is used for parsing, data of the object type will be obtained. 5. a function encapsulated by myself // parameter 1: access URL, parameter 2: post data (GET if not specified), parameter 3: submitted $ cookies, parameter 4: whether to return $ cookie function curl_request ($ url, $ post = '', $ cookie ='', $ returnCookie = 0) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_URL, $ url); curl_setopt ($ curl, CURLOPT_USERAGENT, 'mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0) '); curl_setopt ($ curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ curl, CURLOPT_AUTOREFERER, 1); curl_setopt ($ curl, CURLOPT_REFERER ," http://XXX "); If ($ post) {curl_setopt ($ curl, CURLOPT_POST, 1); curl_setopt ($ curl, CURLOPT_POSTFIELDS, http_build_query ($ post);} if ($ cookie) {curl_setopt ($ curl, CURLOPT_COOKIE, $ cookie);} curl_setopt ($ curl, CURLOPT_HEADER, $ returnCookie); curl_setopt ($ curl, expires, 10); curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, 1); $ data = curl_exec ($ curl); if (curl_errno ($ curl) {return curl_error ($ curl);} cu Rl_close ($ curl); if ($ returnCookie) {list ($ header, $ body) = explode ("\ r \ n", $ data, 2 ); preg_match_all ("/Set \-Cookie :( [^;] *);/", $ header, $ matches ); $ info ['cookies'] = substr ($ matches [1] [0], 1); $ info ['content'] = $ body; return $ info ;} else {return $ data;} has an optional parameter description: Class 1: for the optional parameters of the following options, value should be set to a bool value: option optional value remarks CURLOPT_AUTOREFERER when based on Location: redirection, automatically set Referer: Information in the header. CURLOPT _ BINARYTRANSFER returns native (Raw) output when CURLOPT_RETURNTRANSFER is enabled. when CURLOPT_COOKIESESSION is enabled, curl will pass only one session cookie and ignore other cookies. by default, cURL will return all cookies to the server. session cookie is a cookie used to determine whether a session on the server is valid. when CURLOPT_CRLF is enabled, Unix line breaks are converted into carriage return line breaks. when CURLOPT_DNS_USE_GLOBAL_CACHE is enabled, a global DNS cache is enabled. this option is thread-safe and is enabled by default. CURLOPT_FAILONERROR displays the HTTP status code. by default, the HTTP status code smaller than or equal to 400 is ignored. when CURLOPT_FILETIME is enabled, the system tries to modify the information in the remote document. the result is returned through curl_ge. Return the value of the CURLINFO_FILETIME option of the tinfo () function. curl_getinfo (). when CURLOPT_FOLLOWLOCATION is enabled, the "Location:" returned by the server is put in the header and recursively returned to the server. you can use CURLOPT_MAXREDIRS to limit the number of recursive responses. CURLOPT_FORBID_REUSE force disconnect after interaction is completed and cannot be reused. CURLOPT_FRESH_CONNECT forces a new connection to replace the connection in the cache. when CURLOPT_FTP_USE_EPRT is enabled, the EPRT (or LPRT) command is used when FTP is downloaded. if it is set to FALSE, disable EPRT and LPRT and use the PORT command only. when CURLOPT_FTP_USE_EPSV is enabled, try the EPSV command before returning to PASV mode during FTP transmission. disable the EPSV command when set to FALSE. CURLOPT _ When FTPAPPEND is enabled, append the data to the file instead of overwriting it. the alias of CURLOPT_FTPASCII CURLOPT_TRANSFERTEXT. when CURLOPT_FTPLISTONLY is enabled, only the names of FTP directories are listed. when CURLOPT_HEADER is enabled, the header file information is output as a data stream. request string of the tracking handle when CURLINFO_HEADER_OUT is enabled. available from PHP 5.1.3. CURLINFO _ prefix is intentional (intentional ). when CURLOPT_HTTPGET is enabled, the HTTP method is set to GET. because GET is the default value, it is used only when it is modified. when CURLOPT_HTTPPROXYTUNNEL is enabled, it will be transmitted through the HTTP proxy. when CURLOPT_MUTE is enabled, all modified parameters in the cURL function are restored to the default value. after the connection is established, CURLOPT_NETRC accesses ~ /. The netrc file obtains the user name and password to connect to the remote site. when CURLOPT_NOBODY is enabled, the html body section is not output. CURLOPT_NOPROGRESS enables and disables the curl transfer progress bar. this item is enabled by default. note: PHP automatically sets this option to TRUE. this option should only be changed for debugging purposes. when CURLOPT_NOSIGNAL is enabled, all curls are ignored for signals sent to php. this option is enabled by default during SAPI multi-thread transmission. added to cURL 7.10. when CURLOPT_POST is enabled, a regular POST request is sent, which is of the application/x-www-form-urlencoded type, just like submitting a form. when CURLOPT_PUT is enabled, files can be sent over HTTP. both CURLOPT_INFILE and CURLOPT_INFILESIZE must be set. CURLOPT_RETURNTRANSF ER returns the information obtained by curl_exec () in the form of a file stream, rather than directly outputting it. after CURLOPT_SSL_VERIFYPEER is disabled, cURL is terminated from the server for verification. use the CURLOPT_CAINFO option to set the certificate. use the CURLOPT_CAPATH option to set the certificate Directory. if CURLOPT_SSL_VERIFYPEER (default value: 2) is enabled, set CURLOPT_SSL_VERIFYHOST to TRUE or FALSE. the default value is TRUE starting from cURL 7.10. the installation is bound by default from cURL 7.10. after CURLOPT_TRANSFERTEXT is enabled, the ASCII mode is used for FTP transmission. for LDAP, it retrieves plain text information instead of HTML. in Windows, STDOUT is not set to binary mode. CURLOPT_UNRESTRICTED_AUTH generated by using CURLOPT_FOLLOWLOCATION The username and password information is continuously appended to multiple locations in the header, even if the domain name has changed. when CURLOPT_UPLOAD is enabled, file upload is allowed. when CURLOPT_VERBOSE is enabled, all information is reported and stored in STDERR or the specified CURLOPT_STDERR. class 2: For the following optional options, value should be set to an integer value: option optional value remarks CURLOPT_BUFFERSIZE the size of data read into the cache each time, but this value cannot be filled every time. is added to cURL 7.10. CURLOPT_CLOSEPOLICY is neither CURLCLOSEPOLICY_LEAST_RECENTLY_USED nor CURLCLOSEPOLICY_OLDEST. three other CURLCLOSEPOLICY _ exist, but cURL is not supported yet. CURLOPT_CONNECTTIMEO The wait time before the connection is initiated. if the value is set to 0, the wait time is unlimited. CURLOPT_CONNECTTIMEOUT_MS connection wait time, in milliseconds. if it is set to 0, the system waits for no limit. added to cURL 7.16.2. available from PHP 5.2.3. CURLOPT_DNS_CACHE_TIMEOUT sets the time for saving DNS information in the memory. the default value is 120 seconds. CURLOPT_FTPSSLAUTH FTP authentication method: CURLFTPAUTH_SSL (first try SSL), CURLFTPAUTH_TLS (first try TLS) or CURLFTPAUTH_DEFAULT (for cURL to be determined automatically ). added to cURL 7.12.2. CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (default value, let cURL determine which version to use), CURL_HTTP_VERSION_1_0 (force HTTP/ 1.0) or CURL_HTTP_VERSION_1_1 (force HTTP/1.1 ). the HTTP verification method used by CURLOPT_HTTPAUTH. optional values: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE. you can use the | bitfield (or) operator to separate multiple values. cURL allows the server to select the best value. CURLAUTH_ANY is equivalent to CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. CURLAUTH_ANYSAFE is equivalent to CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. CURLOPT_INFILESIZE Sets the size limit of the uploaded file, in bytes. CURLOPT_LOW_SPEED_LIMIT when the transmission speed is less than CURLOPT_LOW_SPEED_LIMIT (bytes/sec), PHP will determine whether to cancel the transmission because it is too slow based on CURLOPT_LOW_SPEED_TIME. CURLOPT_LOW_SPEED_TIME when the transmission speed is less than CURLOPT_LOW_SPEED_LIMIT (bytes/sec), PHP will determine whether to cancel the transmission because it is too slow based on CURLOPT_LOW_SPEED_TIME. the maximum number of connections allowed by CURLOPT_MAXCONNECTS. if the maximum number is exceeded, CURLOPT_CLOSEPOLICY is used to determine which connections should be stopped. CURLOPT_MAXREDIRS specifies the maximum number of HTTP redirects. this option is used with CURLOPT_FOLLOWLOCATION. CURLOPT_PORT is used to specify the connection end. Port. (optional) bitfield of CURLOPT_PROTOCOLS CURLPROTO. if enabled, the bitfield value limits the protocols that libcurl can use during transmission. this will allow you to support many protocols when compiling libcurl, but only use a subset of them that are allowed to be used. by default, libcurl uses all protocols supported by libcurl. see CURLOPT_REDIR_PROTOCOLS. available protocol options: CURLPROTO_HTTP, CURLPROTO_HTTPS, protocol, CURLPROTO_SCP, protocol, CURLPROTO_TELNET, CURLPROTO_LDAP, protocol, CURLPROTO_FILE, protocol, CURLPROTO_ALL added to cURL 7.19.4. CURLOPT _ PROXYAUTH the authentication method for HTTP proxy connection. use the bitfield flag in CURLOPT_HTTPAUTH to set the corresponding options. for proxy verification, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. added to cURL 7.10.7. CURLOPT_PROXYPORT port of the proxy server. you can also set the port in CURLOPT_PROXY. CURLOPT_PROXYTYPE is either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. is added to cURL 7.10. the bitfield value in CURLOPT_REDIR_PROTOCOLS CURLPROTO. if enabled, the bit field value limits the protocol that the transmission thread can use when CURLOPT_FOLLOWLOCATION is enabled to follow a redirection. this will enable you to use the allowed protocol subset for the redirection time-frame transmission thread. by default, libcurl will allow all except FILE and SCP Protocol. this is different from any supported protocols in the 7.19.4 prerelease. for protocol constants, see CURLOPT_PROTOCOLS. added to cURL 7.19.4. CURLOPT_RESUME_FROM transmits a byte offset (used for resumable data transfer) when the data is resumed ). CURLOPT_SSL_VERIFYHOST 1 check whether there is a common name in the server SSL certificate ). note: the Common Name is generally the domain Name or sub-domain Name you want to apply for the SSL certificate ). 2. check whether the public name exists and matches the provided host name. the SSL version used by CURLOPT_SSLVERSION (2 or 3 ). by default, PHP detects this value by itself, although in some cases you need to manually set it. CURLOPT_TIMECONDITION If no modification is made and the value of CURLOPT_HEADER is true, a 304 Not Modified header is returned, and the value of CURLOPT_HEADER is false, use CURL_TIMECOND_IFUNMODSINCE. the default value is CURL_TIMECOND_IFUNMODSINCE. CURLOPT_TIMEOUT sets the maximum number of seconds that cURL can be executed. CURLOPT_TIMEOUT_MS sets the maximum number of milliseconds that cURL can be executed. added to cURL 7.16.2. it can be used from PHP 5.2.3. CURLOPT_TIMEVALUE sets the timestamp used by CURLOPT_TIMECONDITION. by default, CURL_TIMECOND_IFMODSINCE is used. category 3: optional parameters for the following options, v Alue should be set to a value of the string type: optional value remarks CURLOPT_CAINFO a file name that stores one or more certificates used for server verification. this parameter is only valid when used with CURLOPT_SSL_VERIFYPEER .. CURLOPT_CAPATH is a directory that stores multiple CA certificates. this option is used with CURLOPT_SSL_VERIFYPEER. CURLOPT_COOKIE sets the content of "Cookie:" In the HTTP request. multiple cookies are separated by semicolons with a space (for example, "fruit = apple; color = red "). CURLOPT_COOKIEFILE: name of the file containing the cookie data. the cookie file format can be Netscape, or simply store the HTTP header information to the file. CURLOPT_COOKIEJAR file that saves cookie information after the connection is complete. CU RLOPT_CUSTOMREQUEST uses a custom request information instead of "GET" or "HEAD" as an HTTP request. this is applicable to the execution of "DELETE" or other more concealed HTTP requests. valid values include "GET", "POST", and "CONNECT. that is to say, do not enter the entire HTTP request here. for example, inputting "GET/index.html HTTP/1.0 \ r \ n" is incorrect. note: Do not use this method before determining whether the server supports this custom request. CURLOPT_EGDSOCKET is similar to CURLOPT_RANDOM_FILE, except for one Entropy Gathering Daemon socket. the value of "Accept-Encoding:" In the CURLOPT_ENCODING HTTP request header. supported encodings include "identity", "deflate", and "gzip ". if it is an empty string "", the request header will send all supported encoding types. in cURL 7. 10. CURLOPT_FTPPORT is used to obtain the IP address required by the FTP "POST" command. the "POST" command tells the remote server to connect to our specified IP address. 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: name of the network sending interface, which can be an interface name, IP address, or host name. CURLOPT_KRB4LEVEL KRB4 (Kerberos 4) security level. any values below are valid (in ascending order): "clear", "safe", "confidential", "private ".. if the string does not match any of these, "private" is used ". if this option is set to NULL, KRB4 security authentication is disabled. currently, KRB4 security authentication can only be used for FTP transmission. CURLOPT_POSTFIELDS all data using the "POS" in the HTTP protocol T "operation to send. to send the file, add the @ prefix before the file name and use the complete path. this parameter can be passed through the urlencoded string similar to 'para1 = val1? 2 = val2 &... 'Or an array with the field name as the key value and field data as the value. if the value is an array, the Content-Type header is set to multipart/form-data. CURLOPT_PROXY HTTP proxy channel. CURLOPT_PROXYUSERPWD a string in the format of "[username]: [password]" used to connect to the proxy. CURLOPT_RANDOM_FILE: name of the file used to generate the seed SSL random number. CURLOPT_RANGE is in the form of "X-Y", where X and Y are optional to obtain the range of data, measured in bytes. the HTTP transport thread also supports several such repeated items separated by commas, such as "X-Y, N-M ". the content of CURLOPT_REFERER in the HTTP request header "Referer. CURLOPT_SSL_CIPHER_LIST a list of SSL encryption algorithms. for example, both RC4-SHA and TLSv1 are available encryption lists. CURLOPT_SSLCERT: name of the file containing the PEM certificate. CURLOPT_SSLCERTPASSWD use the password required by the CURLOPT_SSLCERT certificate. the type of the CURLOPT_SSLCERTTYPE certificate. supported formats include "PEM" (default), "DER", and "ENG ". added to cURL 7.9.3. CURLOPT_SSLENGINE is the encryption engine variable used to encrypt the SSL private key specified in CURLOPT_SSLKEY. CURLOPT_SSLENGINE_DEFAULT is a variable used for asymmetric encryption. CURLOPT_SSLKEY contains the name of the SSL private key. CURLOPT_SSLKEYPASSWD specifies the password of the SSL private key in CURLOPT_SSLKEY. note: Because this option contains sensitive password information, ensure the security of this PHP script. the encryption type of the private key specified in CURLOPT_SSLKEY. the supported key types are "PEM" (default), "DER", and "ENG ". you can also set the URL to be obtained in the curl_init () function. CURLOPT_USERAGENT contains a "User-Agent:" header string in the HTTP request. CURLOPT_USERPWD transmits the username and password required for a connection. Format: "[username]: [password]". category 4: for the following optional options, value should be set with an array: option optional value remarks CURLOPT_HTTP200ALIASES 200 response code array. is the response in the array considered correct, otherwise it is regarded as wrong. added to cURL 7.10.3. CURLOPT_HTTPHEADER is an array used to set HTTP header fields. use an array in the following format: array ('content-type: text/plain ', 'Content-length: 100') CURLOPT_POSTQUOTE after the FTP request is executed, A group of FTP commands executed on the server. CURLOPT_QUOTE a group of FTP commands executed on the server prior to FTP requests. for the optional parameters of the following options, value should be set as a stream resource (for example, using fopen (): the optional value of the option CURLOPT_FILE is used to set the location of the output file, the value is a resource type. the default value is STDOUT (browser ). CURLOPT_INFILE: the address of the file to be read when uploading a file. The value is a resource type. CURLOPT_STDERR sets an error output address. The value is a resource type, replacing the default STDERR. CURLOPT_WRITEHEADER sets the file address for writing part of the header content. The value is a resource type. for the optional parameters of the options below, value should be set as a callback function name: option optional value CURLOPT_HEADERFUNCTION sets a callback function, which has two parameters, the first is the resource handle of cURL, and the second is the output header data. the output of header data must depend on this function to return the size of written data. CURLOPT_PASSWDFUNCTION sets a callback function with three parameters: the first is the resource handle of cURL, the second is a password prompt, and the third parameter is the maximum allowed password length. returns the password value. CURLOPT_PROGRESSFUNCTION sets a callback function with three parameters: the first is the resource handle of cURL, the second is a file descriptor resource, and the third is the length. returns the contained data. CURLOPT_READFUNCTION has two callback functions. The first is the session handle, and the second is the string of the HTTP response header information. using this function, you can process the returned data. the returned value is the data size in bytes. 0 indicates the EOF signal. CURLOPT_WRITEFUNCTION
Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.