Curl command line options. Sharpening your skills with cURL

CURL is a package software, consisting of a command line utility and a library for passing data using URL syntax.

CURL supports many protocols, including DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP.

Upload separate file
The following command will get the contents of the URL and display it on standard output (i.e. your terminal).

Curl https://mi-al.ru/ > mi-al.htm % Total % Received % Xferd Average Speed ​​Time Time Time Current Dload Upload Total Spent Left Speed ​​100 14378 0 14378 0 0 5387 0 --:--:- - 0:00:02 --:--:-- 5387

Saving cURL output to a file
We can save the result of the curl command to a file using the -o/-O options.
  • -o(o lowercase) the result will be saved in the file specified in command line
  • -O(uppercase O) file name will be taken from the URL and will be used to save the received data.

$ curl -o mygettext.html http://www.gnu.org/software/gettext/manual/gettext.html

The gettext.html page will now be saved in a file called 'mygettext.html'. When curl is run with the -o option, it displays the download progress bar as follows.

% Total % Received % Xferd Average Speed ​​Time Time Time Current Dload Upload Total Spent Left Speed ​​66 1215k 66 805k 0 0 33060 0 0:00:37 0:00:24 0:00:13 45900 100 1215k 100 1215k 0 0 39474 0 0:00:31 0:00:31 --:--:-- 68987

When you use curl -O (upper case O), it will itself save the content to a file called ‘gettext.html’ on the local machine.

$ curl -O http://www.gnu.org/software/gettext/manual/gettext.html

Note: When curl needs to write data to the terminal, it disables the progress bar to avoid confusion with the printed data. We can use the '>'|'-o'|'-O' options to transfer the results to a file.

Retrieving multiple files at once
We can download multiple files at one time by specifying all the URLs on the command line.

Curl -O URL1 -O URL2

The below command will download both index.html and gettext.html and save them with the same names in the current directory.

Curl -O http://www.gnu.org/software/gettext/manual/html_node/index.html -O http://www.gnu.org/software/gettext/manual/gettext.html

Please note, when we download multiple files from the same server as shown above, curl will try to reuse the connection.

Follow HTTP Location headers with -L option
By default, CURL does not follow HTTP Location in headers (redirects). When the requested web page is moved to another location, the corresponding response will be sent in the HTTP Location headers.
For example, when someone types google.com into their browser from their country, they will automatically be redirected to 'google.co.xx'. This is done based on the HTTP Location header as shown below.

Curl https://www.google.com/?gws_rd=ssl

302 Moved

302 Moved

The document has moved here.

The above output says that the requested document has been moved to ‘

Hidden from guests

.
You can tell curl to follow redirects, this is done using the -L option as shown below. Will now be loaded source html with

Hidden from guests

.

Curl -L https://www.google.com/?gws_rd=ssl

Renewing a previous download

Using the -C option you can continue a download that was stopped for some reason. This will be useful when downloading large files fails.
If we say '-C -', then curl will look for where to resume downloading from. We can also specify '-C<смещение>’. The specified byte offset will be skipped from the beginning of the source file.
Get started large load with curl and press Ctrl-C to stop mid-download.

$ curl -O http://www.gnu.org/software/gettext/manual/gettext.html ############## 20.1%

Injection was stopped at 20.1%. Using “curl -C -” we can continue loading from where we left off. Now the download will continue from 20.1%.

Curl -C - -O http://www.gnu.org/software/gettext/manual/gettext.html ############### 21.1%

Data rate limit
You can limit the data transfer rate with the –limit-rate option. You can pass the maximum speed as an argument.

$ curl --limit-rate 1000B -O http://www.gnu.org/software/gettext/manual/gettext.html

The command above will limit the transfer rate to 1000 bytes/second. curl can use higher speeds in peaks. But the average speed will be approximately 1000 bytes/second.
Below is the progress bar for the command above. You can see that the current speed is around 1000 bytes.

% Total % Received % Xferd Average Speed ​​Time Time Time Current Dload Upload Total Spent Left Speed ​​1 1215k 1 13601 0 0 957 0 0:21:40 0:00:14 0:21:26 999 1 1215k 1 14601 0 0 960 0 0:21:36 0:00:15 0:21:21 999 1 1215k 1 15601 0 0 962 0 0:21:34 0:00:16 0:21:18 999

Load a file only if it was changed before/after a specified time
You can get files that have changed after a certain time using the -z option in curl. This will work for both FTP and HTTP.

The command above will only load yy.html if it has been modified more recently than the given date and time.

The command above will load file.html if it has been modified before the given date and time. Type 'man curl_getdate' to learn more about the different supported syntaxes for date expressions.

Passing HTTP authentication in cURL
Sometimes websites require a username and password to view their content. Using the -u option, you can pass these credentials from cURL to the web server as shown below.

$ curl -u username:password URL

Note: By default, curl uses HTTP basic authentication. We can set other authentication methods using –ntlm | –digest.


cURL can also be used to download files from FTP servers. If the specified FTP path is a directory, then by default a list of files in it will be displayed.

$ curl -u ftpuser:ftppass -O ftp://ftp_server/public_html/xss.php

The above command will download the xss.php file from the ftp server and save it in a local directory.

$ curl -u ftpuser:ftppass -O ftp://ftp_server/public_html/

Here the URL refers to a directory. Therefore, cURL will list files and directories at the given URL.


CURL supports ranges specified in URLs. When a range is given, the corresponding files within that range will be loaded. This will be useful when downloading packages from FTP mirror sites.

$ curl ftp://ftp.uk.debian.org/debian/pool/main//

The command above will list all packages in a-z range in the terminal.

Uploading files to an FTP server
Curl can also be used to upload to an FTP server with the -T option.

$ curl -u ftpuser:ftppass -T myfile.txt ftp://ftp.testserver.com

The above command will upload a file named myfile.txt to the FTP server. You can also upload multiple files at once using ranges.

$ curl -u ftpuser:ftppass -T "(file1,file2)" ftp://ftp.testserver.com

Optionally we can use “.” to receive from standard input and pass it to the remote machine.

$ curl -u ftpuser:ftppass -T - ftp://ftp.testserver.com/myfile_1.txt

The above command will receive the output from the user from standard input and store the contents on the ftp server as 'myfile_1.txt'.
You can specify '-T' for each URL, and each address-file pair will determine what to upload where

More information with increased verbosity and trace option
You can find out what's going on using the -v option. The -v option enables verbal mode and will print details.

Curl -v https://www.google.co.th/?gws_rd=ssl

The command above will output the following

* Rebuilt URL to: https://www.google.co.th/?gws_rd=ssl * Hostname was NOT found in DNS cache * Trying 27.123.17.49... * Connected to www.google.co.th (27.123.17.49) port 80 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.38.0 > Host : www.google.co.th > Accept: */* >< HTTP/1.1 200 OK < Date: Fri, 14 Aug 2015 23:07:20 GMT < Expires: -1 < Cache-Control: private, max-age=0 < Content-Type: text/html; charset=windows-874 < P3P: CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info." * Server gws is not blacklisted < Server: gws < X-XSS-Protection: 1; mode=block < X-Frame-Options: SAMEORIGIN < Set-Cookie: PREF=ID=1111111111111111:FF=0:TM=1439593640:LM=1439593640:V=1:S=FfuoPPpKbyzTdJ6T; expires=Sun, 13-Aug-2017 23:07:20 GMT; path=/; domain=.google.co.th ... ... ...

If you need more detailed information, then you can use the –trace option. The –trace option will enable a full trace dump of all incoming/outgoing data for a given file



CURL is a software package consisting of a command line utility and a library for transferring data using URL syntax.

CURL supports many protocols, including DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP.

Upload separate file
The following command will get the contents of the URL and display it on standard output (i.e. your terminal).

Curl https://mi-al.ru/ > mi-al.htm % Total % Received % Xferd Average Speed ​​Time Time Time Current Dload Upload Total Spent Left Speed ​​100 14378 0 14378 0 0 5387 0 --:--:- - 0:00:02 --:--:-- 5387

Saving cURL output to a file
We can save the result of the curl command to a file using the -o/-O options.
  • -o(o lower case) the result will be saved in the file specified on the command line
  • -O(uppercase O) file name will be taken from the URL and will be used to save the received data.

$ curl -o mygettext.html http://www.gnu.org/software/gettext/manual/gettext.html

The gettext.html page will now be saved in a file called 'mygettext.html'. When curl is run with the -o option, it displays the download progress bar as follows.

% Total % Received % Xferd Average Speed ​​Time Time Time Current Dload Upload Total Spent Left Speed ​​66 1215k 66 805k 0 0 33060 0 0:00:37 0:00:24 0:00:13 45900 100 1215k 100 1215k 0 0 39474 0 0:00:31 0:00:31 --:--:-- 68987

When you use curl -O (upper case O), it will itself save the content to a file called ‘gettext.html’ on the local machine.

$ curl -O http://www.gnu.org/software/gettext/manual/gettext.html

Note: When curl needs to write data to the terminal, it disables the progress bar to avoid confusion with the printed data. We can use the '>'|'-o'|'-O' options to transfer the results to a file.

Retrieving multiple files at once
We can download multiple files at one time by specifying all the URLs on the command line.

Curl -O URL1 -O URL2

The below command will download both index.html and gettext.html and save them with the same names in the current directory.

Curl -O http://www.gnu.org/software/gettext/manual/html_node/index.html -O http://www.gnu.org/software/gettext/manual/gettext.html

Please note, when we download multiple files from the same server as shown above, curl will try to reuse the connection.

Follow HTTP Location headers with -L option
By default, CURL does not follow HTTP Location in headers (redirects). When the requested web page is moved to another location, the corresponding response will be sent in the HTTP Location headers.
For example, when someone types google.com into their browser from their country, they will automatically be redirected to 'google.co.xx'. This is done based on the HTTP Location header as shown below.

Curl https://www.google.com/?gws_rd=ssl

302 Moved

302 Moved

The document has moved here.

The above output says that the requested document has been moved to ‘

Hidden from guests

.
You can tell curl to follow redirects, this is done using the -L option as shown below. Now the original will be loaded html code With

Hidden from guests

.

Curl -L https://www.google.com/?gws_rd=ssl

Renewing a previous download

Using the -C option you can continue a download that was stopped for some reason. This will be useful when downloading large files fails.
If we say '-C -', then curl will look for where to resume downloading from. We can also specify '-C<смещение>’. The specified byte offset will be skipped from the beginning of the source file.
Start a large download with curl and press Ctrl-C to stop it mid-download.

$ curl -O http://www.gnu.org/software/gettext/manual/gettext.html ############## 20.1%

Injection was stopped at 20.1%. Using “curl -C -” we can continue loading from where we left off. Now the download will continue from 20.1%.

Curl -C - -O http://www.gnu.org/software/gettext/manual/gettext.html ############### 21.1%

Data rate limit
You can limit the data transfer rate with the –limit-rate option. You can pass the maximum speed as an argument.

$ curl --limit-rate 1000B -O http://www.gnu.org/software/gettext/manual/gettext.html

The command above will limit the transfer rate to 1000 bytes/second. curl can use higher speeds in peaks. But the average speed will be approximately 1000 bytes/second.
Below is the progress bar for the command above. You can see that the current speed is around 1000 bytes.

% Total % Received % Xferd Average Speed ​​Time Time Time Current Dload Upload Total Spent Left Speed ​​1 1215k 1 13601 0 0 957 0 0:21:40 0:00:14 0:21:26 999 1 1215k 1 14601 0 0 960 0 0:21:36 0:00:15 0:21:21 999 1 1215k 1 15601 0 0 962 0 0:21:34 0:00:16 0:21:18 999

Load a file only if it was changed before/after a specified time
You can get files that have changed after a certain time using the -z option in curl. This will work for both FTP and HTTP.

The command above will only load yy.html if it has been modified more recently than the given date and time.

The command above will load file.html if it has been modified before the given date and time. Type 'man curl_getdate' to learn more about the different supported syntaxes for date expressions.

Passing HTTP authentication in cURL
Sometimes websites require a username and password to view their content. Using the -u option, you can pass these credentials from cURL to the web server as shown below.

$ curl -u username:password URL

Note: By default, curl uses HTTP basic authentication. We can set other authentication methods using –ntlm | –digest.


cURL can also be used to download files from FTP servers. If the specified FTP path is a directory, then by default a list of files in it will be displayed.

$ curl -u ftpuser:ftppass -O ftp://ftp_server/public_html/xss.php

The above command will download the xss.php file from the ftp server and save it in a local directory.

$ curl -u ftpuser:ftppass -O ftp://ftp_server/public_html/

Here the URL refers to a directory. Therefore, cURL will list files and directories at the given URL.


CURL supports ranges specified in URLs. When a range is given, the corresponding files within that range will be loaded. This will be useful when downloading packages from FTP mirror sites.

$ curl ftp://ftp.uk.debian.org/debian/pool/main//

The command above will list all packages in the range a-z in the terminal.

Uploading files to an FTP server
Curl can also be used to upload to an FTP server with the -T option.

$ curl -u ftpuser:ftppass -T myfile.txt ftp://ftp.testserver.com

The above command will upload a file named myfile.txt to the FTP server. You can also upload multiple files at once using ranges.

$ curl -u ftpuser:ftppass -T "(file1,file2)" ftp://ftp.testserver.com

Optionally we can use “.” to receive from standard input and pass it to the remote machine.

$ curl -u ftpuser:ftppass -T - ftp://ftp.testserver.com/myfile_1.txt

The above command will receive the output from the user from standard input and store the contents on the ftp server as 'myfile_1.txt'.
You can specify '-T' for each URL, and each address-file pair will determine what to upload where

More information with increased verbosity and trace option
You can find out what's going on using the -v option. The -v option enables verbal mode and will print details.

Curl -v https://www.google.co.th/?gws_rd=ssl

The command above will output the following

* Rebuilt URL to: https://www.google.co.th/?gws_rd=ssl * Hostname was NOT found in DNS cache * Trying 27.123.17.49... * Connected to www.google.co.th (27.123. 17.49) port 80 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.38.0 > Host: www.google.co.th > Accept: */* >< HTTP/1.1 200 OK < Date: Fri, 14 Aug 2015 23:07:20 GMT < Expires: -1 < Cache-Control: private, max-age=0 < Content-Type: text/html; charset=windows-874 < P3P: CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info." * Server gws is not blacklisted < Server: gws < X-XSS-Protection: 1; mode=block < X-Frame-Options: SAMEORIGIN < Set-Cookie: PREF=ID=1111111111111111:FF=0:TM=1439593640:LM=1439593640:V=1:S=FfuoPPpKbyzTdJ6T; expires=Sun, 13-Aug-2017 23:07:20 GMT; path=/; domain=.google.co.th ... ... ...

If you need more detailed information, then you can use the –trace option. The –trace option will enable a full trace dump of all incoming/outgoing data for a given file



CURL is a command line tool for receiving or sending data using URL syntax.

If you work in a help desk, you should be able to use cURL commands to troubleshoot web applications. cURL is a cross-platform utility for Windows, MAC and UNIX.
Below are some commonly used syntax examples.

1. Check if the URL can be connected

If you are on a UNIX system and are trying to connect to an external URL, then first check that you can access the resource via curl . To do this, use the following command:

# curl yoururl.com

2. Saving the URL/URI output to a file

# curl yoururl.com > yoururl.html

For example:

# curl 74.125.68.100 >/tmp/google.html

The above example will save all content from host 74.125.68.100 to the file /tmp/google.html.

3. Show request and response header

If you want to make sure you receive the expected request and response header, use the following command:

# curl -v yoururl.com

For example:

# curl -v 74.125.68.100 * About to connect() to 74.125.68.100 port 80 (#0) * Trying 74.125.68.100... * Connected to 74.125.68.100 (74.125.68.100) port 80 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.29.0 >Host: 74.125.68.100 >Accept: */* >< HTTP/1.1 200 OK

4. Download at maximum speed

If you want to know how long it takes to download at a certain speed, then use the following command:

# curl --limit-rate 2000B

For example:

# curl --limit-rate 2000B 74.125.68.100

5. Using a proxy to connect

If you need to check whether a proxy server can be used, use the following syntax:

# curl --proxyyourproxy:port http://yoururl.com

6. Checking the URL by entering a title

To fix a specific problem, you can use Curl to insert your data into the header. Consider the following example request with Content-Type:

# curl --header "Content-Type: application/json" http://yoururl.com

We are asking curl to pass the Content-Type as application/json in the request header.

7. Add an additional header

You can add a header to a request using the -header syntax.

# curl --header “X-CustomHeader: GeekFlare” http://yoururl.com

For example:

# curl -v --header "X-CustomHeader: GeekFlare" 74.125.68 * About to connect() to 74.125.68.100 port 80 (#0) * Trying 74.125.68.100... * Connected to 74.125.68.100 (74.125. 68.100) port 80 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.29.0 >Host: 74.125.68.100 >Accept: */* > X-CustomHeader: GeekFlare >< HTTP/1.1 200 OK

8. Open only the response header

If you want to quickly check the response header, then you can use the following syntax to do so.

# curl --head http://yoururl.com

# curl -I 74.125.68.100 HTTP/1.1 200 OK Date: Sun, 18 Jan 2015 08:31:22 GMT Expires: -1 Cache-Control: private, max-age=0 Content-Type: text/html; charset=ISO-8859-1 Set-Cookie: NID=67=SpnXKTDUhw7QGakIeLxmDSF; expires=Mon, 20-Jul-2015 08:31:22 GMT; path=/; domain=.; HttpOnly P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for moreinfo." Server: gws X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN Alternate-Protocol: 80:quic,p=0.02 Transfer-Encoding: chunked Accept-Ranges: none Vary: Accept-Encoding #

9. Connect HTTPS/SSLURL address and ignore any SSL certificate errors

If you need to access an https URL that is throwing a certificate error due to a hostname mismatch, you can use the following syntax.

curl --insecure https://yoururl.com

10. Connect using a specific protocol (SSL/TLS)

To connect to a URL using SSL V2/V3 or TLS only, use the following syntax.

To connect using SSLV2:

# curl --sslv2 https://yoururl.com

To connect using SSLV3:

# curl --sslv3 https://yoururl.com

To connect via TLS:

# curl --tlsv1 https://yoururl.com

11. Upload file from FTP server

Using cURL, you can download a file from an ftp server by providing a username and password.

# curl -u user:password -O ftp://ftpurl/style.css

You can always use "-v" with any syntax to output in verbose mode.

Using cURL online

Yes it is possible. You can execute cURL remotely using the following tools.
Online CURL is a compact tool for extracting an online URL and adding the following parameters.

Connect-timeout --cookie --data --header --head --location --max-time --proxy --request --user --url --user-agent

Example output:

cURL command line builder – Allows you to create a cURL command that you can use to enter information into the user interface.

Real practical example: you need to reboot your router (modem) to change the IP address. To do this, you need to: log in to the router, go to the maintenance page and click the “Reboot” button. If this action needs to be performed several times, then the procedure must be repeated. Agree, you don’t want to do this routine manually every time. cURL allows you to automate all of this. With just a few cURL commands you can achieve authorization and complete the task on the router.

  • cURL is useful for retrieving data from websites on the command line.
Another practical example: we want to implement the display of general statistics for several sites. If we use cURL, then this becomes a completely trivial task: using cURL we authenticate on the statistics collection service (if required), then (again using cURL commands) we obtain the necessary pages, parse the data we need; the procedure is repeated for all our sites, then we add and display the final result.

Those. cases of using cURL are quite real, although, in the majority, cURL is needed by programmers who use it for their programs.

CURL supports many protocols and authorization methods, can transfer files, works correctly with cookies, supports SSL certificates, proxies and much more.

cURL in PHP and command line

We can use cURL in two main ways: in PHP scripts and on the command line.

To enable cURL in PHP on the server, you need to uncomment the line in the php.ini file

Extension=php_curl.dll

And then reboot the server.

On Linux you need to install the curl package.

On Debian, Ubuntu or Linux Mint:

$ sudo apt-get install curl


On Fedora, CentOS or RHEL:

$ sudo yum install curl

To clearly see the difference in use in PHP and on the command line, we will perform the same tasks twice: first in the PHP script, and then on the command line. Let's try not to get confused.

Retrieving data using cURL

Retrieving data using cURL in PHP

Example in PHP:

Everything is very simple:
$target_url- the address of the site that interests us. After the site address, you can put a colon and add the port address (if the port is different from the standard one).

curl_init- initializes a new session and returns a handle, which in our example is assigned to a variable $ch.

We then execute the request with the cURL function curl_exec, to which a descriptor is passed as a parameter.

Everything is very logical, but when this script is executed, the contents of the site will be displayed on our page. But what if we don’t want to display the content, but want to write it to a variable (for subsequent processing or parsing).

Let's add a little to our script:

0) ( echo "Curl error: " . curl_error($ch); ) curl_close($ch); ?>

We have a line curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);.

curl_setopt- sets options. A complete list of options can be found on this page:

Hidden from guests

$response_data = curl_exec($ch);

Now the script value is assigned to the $response_data variable, with which further operations can be performed. For example, you can display its contents.

Stitches

If (curl_errno($ch) > 0) ( echo "Curl error: " . curl_error($ch); )

serve for debugging in case errors occur.

Retrieving data using cURL on the command line

On the command line, just type

where instead of mi-al.ru- the address of your website.

If you need to copy data into a variable rather than display the result on the screen, then do this:

Temp="curl mi-al.ru"

However, some data is still displayed:

To prevent them from being displayed, add the key -s:

Temp="curl -s mi-al.ru"

You can see what has been recorded:

Echo $temp | less

Basic and HTTP authentication

Authentication, simply put, is entering a username and password.

Basic authentication is server-based authentication. For this, two files are created: .htaccess And .htpasswd

The contents of the .htaccess file are something like this

AuthName "For registered users only!" AuthType Basic require valid-user AuthUserFile /home/freeforum.biz/htdocs/.htpassw


The contents of the .htpasswd file are something like this:

Mial:CRdiI.ZrZQRRc

Those. login and password hash.

When you try to access a password-protected folder, the browser will display something like this:

HTTP authentication is the case when we enter a login and password into a form on a website. It is this authentication that is used when logging into mail, forums, etc.

Basic cURL authentication (PHP)

There is a website

Hidden from guests

Let's try our initial script:

0) ( echo "Curl error: " . curl_error($ch); ) else ( echo $response_data; ) curl_close($ch); ?>

Although the script believes that there is no error, we don’t like the output at all:

Add two lines:

Curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, "ru-board:ru-board");

The first line we set the authentication type - basic. The second line contains the name and password separated by a colon (in our case, the name and password are the same - ru-board). It turned out like this:

0) ( echo "Curl error: " . curl_error($ch); ) else ( echo $response_data; ) curl_close($ch); ?> Let's try: 30946 Great! Basic cURL authentication (on the command line) The same can be achieved on the command line with one line: curl -u ru-board:ru-board http://62.113.208.29/Update_FED_DAYS/

I didn't forget to specify the authentication type, it's just that in cURL the basic authentication type is the default.

Everything worked out so quickly on the command line that, out of frustration, I wrote the following program. She connects to the site and downloads the latest update:

Temp=`curl -s -u ru-board:ru-board http://62.113.208.29/Update_FED_DAYS/ | grep -E -o "Update_FED_201(1).(2).(2).7z" | uniq | tail -n 1`; curl -o $temp -u ru-board:ru-board http://62.113.208.29/Update_FED_DAYS/$temp

With just a few more commands you can add:

  • unpacking the archive into the specified directory;
  • launching ConsultantPlus updates (these are updates for it);
  • you can check whether the latest available update has already been downloaded or a new one has appeared;
  • add it all to Cron for daily updates.
HTTP authentication cURL

HTTP cURL authentication in PHP

We need to know:

  • address where to send authentication data
  • sending method GET or POST
  • login
  • password
Sometimes this data is not enough. Let's figure it out.

The address where you need to send the data can be taken from the authentication form. For example:

We are looking at the property action. Those. the final page is login.php. We need the full address, like this

Hidden from guests

Here we also find the sending method: method="post"

I also know the login and password: admin and qwerasdfzxcv
Those. A string is sent to the server from the form using the POST method. Theoretically, our previous script, to which we added a new line, should work. Those. authentication must occur.

0) ( echo "Curl error: " . curl_error($ch); ) else ( ) curl_close($ch); ?>

New line in script

curl_setopt($ch, CURLOPT_POSTFIELDS, "LOGIN_USER=admin&LOGIN_PASSWD=qwerasdfzxcv");

Here curl_setopt- a function that is already familiar to us for setting options for cURL, CURLOPT_POSTFIELDS- this is the name of the option we are setting. CURLOPT_POSTFIELDS contains all data that is transferred using the POST method. Well, the line itself LOGIN_USER=admin&LOGIN_PASSWD=qwerasdfzxcv- this is the same data that we transmit.

If you carefully examine the form, you will see that it also contains hidden fields. And the data can be processed or supplemented with JavaScript. You can study all this, but I prefer a simpler method.

I'm using Wireshark. This program is designed to sniff (intercept) traffic. And it is in it that it is very convenient to see what exactly is being transmitted to the site.

Watch this tiny video:


Those. with the address where the data is transferred, I guessed right. But the transmitted string turned out to be much more complicated.

I entered the correct parameter, and also slightly modified the script so that it not only logs in, but also receives something from the router:

0) ( echo "Curl error: " . curl_error($ch); ) else ( $target_url2 = "http://188.35.8.64:8080/bsc_wlan.php"; $ch2 = curl_init($target_url2); curl_setopt($ ch2, CURLOPT_RETURNTRANSFER, 1); $response_data2 = curl_exec($ch2); preg_match("|f.ssid.value = "(.*)";|", $response_data2, $results2); $results2 = str_replace("f .ssid.value = "", "", $results2); $results2 = str_replace("";", "", $results2); echo "Wi-fi network name: $results2
"; preg_match("|f_wpa.wpapsk1.value(.*)";|", $response_data2, $results3); $results3 = str_replace("f_wpa.wpapsk1.value", "", $results3); $results3 = str_replace("="", "", $results3); $results3 = str_replace("";", "", $results3); echo "Wi-Fi network password: $results3"; ) curl_close($ch); ?>

By the way, if the owner updates the password (but does not update the firmware), then the new password can always be viewed at

Hidden from guests

(This is a well-known vulnerability in the D-Link DIR-300, D-Link DIR-320, and D-Link DAP-1353 routers).

HTTP cURL authentication on the command line

We already know the full address, as well as the string to be transmitted. So it's simple:

Curl --data "ACTION_POST=LOGIN&FILECODE=&VERIFICATION_CODE=&LOGIN_USER=admin&LOGIN_PASSWD=qwerasdfzxcv&login=Log+In+&VER_CODE=" http://188.35.8.64:8080/login.php

I think everything is clear, since we have already considered these deadlines. If anyone doesn’t understand, ask in the comments.

An example of using cURL to retrieve and parse data would be the following set of commands:

Curl -s --data "ACTION_POST=LOGIN&FILECODE=&VERIFICATION_CODE=&LOGIN_USER=admin&LOGIN_PASSWD=qwerasdfzxcv&login=Log+In+&VER_CODE=" http://188.35.8.64:8080/login.php > /dev/null && echo -e "nn " && echo "Wi-Fi network name" && curl -s http://188.35.8.64:8080/bsc_wlan.php | grep -E "f.ssid.value = "(.)*";" | sed "s/f.ssid.value = "//" | sed "s/";//" && echo "Wi-Fi network password" && curl -s http://188.35.8.64:8080/bsc_wlan.php | grep -E "f_wpa.wpapsk1.(.)*";" | sed "s/f_wpa.wpapsk1.value//" | sed "s/";//" | sed "s/="//"

It would be more correct to write this heading as follows: “Complex” authorization cases. Those. Put the word “complicated” in quotation marks. They seem complicated only at first glance, when it is not clear: where the sending occurs, what field names are, what exactly is sent, etc.

But, in fact, they all come down to the POST or GET methods. To understand what exactly is being sent, you can save the page with the form to your disk and add a function to display the data generated for sending to the submit button. Or even simpler - like me, Wireshark.

If the data is correct, but authentication does not occur, then you need to dig in the following directions:

  • set the correct referrer string
  • set the "correct" user agent string.
All this can be done using basic cURL methods, but I won’t go into that. The lesson was already long enough, but I also wanted to show a couple of tricks with cURL.

Tips and tricks cURL

cURL and receiving cookies in addition to CURLOPT_COOKIEJAR

I think it's already clear that cURL handles cookies correctly - stores them, uses them when the server requests them, etc. But sometimes cookies need to be saved. There is an option for this called CURLOPT_COOKIEJAR, but it is not always possible to use it. This is what our first trick is dedicated to.

Sometimes, due to the way PHP is configured on the server, options such as CURLOPT_COOKIEJAR (allows you to save received cookies to a file) and CURLOPT_COOKIEFILE (allows you to use cookies from a file) are not available to us. Because they say that using these options we can steal any file from their server. Here is the solution to this problem:

1) We do not use CURLOPT_FOLLOWLOCATION
2) Use curl_setopt($ch, CURLOPT_HEADER, 1)
3) Collect cookies from the header like this:

Preg_match_all("|Set-Cookie: (.*);|U", $content, $results); $cookies = implode(";", $results);

4) Set them using curl_setopt($ch, CURLOPT_COOKIE, $cookies);

Second tip. We can turn from attackers into victims. To avoid becoming a victim of a man-in-the-middle attack, we do this.

Please, everyone, stop setting the CURLOPT_SSL_VERIFYPEER setting to false or 0. If your PHP installation does not have an up-to-date set of root CA certificates, download one from the curl website and save it to your server:

Hidden from guests

Then set the path in your php.ini file, for example on Windows:

Curl.cainfo=c:phpcacert.pem

Disabling CURLOPT_SSL_VERIFYPEER allows for a man-in-the-middle (MITM) attack, which we don't want!

Well, the last tip for today. Did you know that a large number of asynchronous curl requests are possible?

For this you can use curl_multi_init. Details and example code in the official documentation

Hidden from guests

Hidden from guests


About cURL on the command line

Hidden from guests


The second part of the cURL lesson has also been prepared for reading in Russian: "".

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_setopt — Sets a parameter for the CURL session

List of parameters

cURL handle obtained from curl_init().

Parameter to be set CURLOPT_XXX.

The value of the option parameter.

bool:

Parameter Notes
CURLOPT_AUTOREFERER TRUE for automatic field setting Referrer: in requests redirected by header Location:.
CURLOPT_BINARYTRANSFER TRUE to return the raw response when using a constant CURLOPT_RETURNTRANSFER. As of PHP 5.1.3 this option is no longer required: raw output is always returned when using the option CURLOPT_RETURNTRANSFER.
CURLOPT_COOKIESESSION TRUE to instruct the current session to start a new "session" of cookies. This will cause libcurl to ignore any "session" cookies it should have loaded from the previous session. By default, libcurl always saves and loads all cookies, regardless of whether they are "session" or not. "Session" cookies are cookies that do not expire and must only exist for the current "session".
CURLOPT_CERTINFO TRUE to output SSL certificate information to stream STDERR with secure connections. Added in cURL 7.19.1. Available starting from PHP 5.3.2. Requires this option to be enabled for correct operation CURLOPT_VERBOSE.
CURLOPT_CONNECT_ONLY TRUE tells the library to perform the necessary proxy authentication and connection setup, but does not transmit data. This option is implemented for HTTP, SMTP and POP3. Added in 7.15.2. Available from PHP 5.5.0.
CURLOPT_CRLF TRUE to convert Unix line endings to CRLF.
CURLOPT_DNS_USE_GLOBAL_CACHE TRUE to use the global DNS cache. This option is not thread safe and is enabled by default.
CURLOPT_FAILONERROR TRUE for a detailed report on failure if the received HTTP code is greater than or equal to 400. The default behavior returns the page as normal, ignoring the code.
CURLOPT_FILETIME TRUE to try to obtain the modification date of a remote document. This value can be obtained using the CURLINFO_FILETIME parameter from the function curl_getinfo().
CURLOPT_FOLLOWLOCATION TRUE to follow any heading "Location: " sent by the server in its response (note that this happens recursively, PHP will follow any headers sent "Location: ", except when a constant is set CURLOPT_MAXREDIRS).
CURLOPT_FORBID_REUSE TRUE to force a connection to be closed after its processing has completed so that it cannot be reused.
CURLOPT_FRESH_CONNECT TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT TRUE to use EPRT (and LPRT) for active FTP uploads. Use FALSE in order to disable EPRT and LPRT and use only PORT.
CURLOPT_FTP_USE_EPSV TRUE for initial testing of the EPSV command during FTP transfers. If the command fails, it will fall back to PASV. Install in FALSE to disable EPSV.
CURLOPT_FTP_CREATE_MISSING_DIRS TRUE to create missing directories if an FTP operation encounters a non-existent path.
CURLOPT_FTPAPPEND TRUE to write a remote file to the end, instead of overwriting it over an existing file.
CURLOPT_TCP_NODELAY Permanently specifies whether the TCP_NODELAY option should be set or cleared (1 = set, 0 = cleared). By default the option is cleared. Available from PHP 5.2.1 for versions built with libcurl 7.11.2 or later.
CURLOPT_FTPASCII Nickname CURLOPT_TRANSFERTEXT. Use this instead.
CURLOPT_FTPLISTONLY TRUE to return only a list of names from the FTP directory.
CURLOPT_HEADER TRUE to include headers in the output.
CURLINFO_HEADER_OUT TRUE to track the handle query string. Available starting from PHP 5.1.3. Prefix CURLINFO_ used specifically.
CURLOPT_HTTPGET TRUE to reset the HTTP request method to the GET method. Since GET is the default, this parameter is only needed if the request method has previously been changed.
CURLOPT_HTTPPROXYTUNNEL TRUE to tunnel through the specified HTTP proxy.
CURLOPT_MUTE TRUE to completely disable cURL function messages. Removed in cURL 7.15.5 (CURLOPT_RETURNTRANSFER option can be used)
CURLOPT_NETRC TRUE to read the ~/.netrc file for the login and password for the remote site with which the connection is being established.
CURLOPT_NOBODY TRUE to exclude the response body from the output. The request method is set to HEAD. Changing this setting to FALSE doesn't change it back to GET.
CURLOPT_NOPROGRESS

TRUE to disable the progress indicator on cURL transfers.

Comment:

PHP automatically sets this parameter to TRUE, change it only for debugging purposes.

CURLOPT_NOSIGNAL TRUE to ignore any cURL function that sends signals to the PHP process. This option is enabled by default in multi-threaded SAPIs to allow timeout parameters to work correctly.
CURLOPT_POST TRUE to use regular HTTP POST. This POST method uses the normal , commonly used in HTML forms.
CURLOPT_PUT TRUE to download a file using the HTTP PUT method. The file used must be set using the options CURLOPT_INFILE And CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER TRUE to return the result of the transfer as a string from curl_exec() instead of direct output to the browser.
CURLOPT_SAFE_UPLOAD TRUE to disable prefix support @ for downloaded files in CURLOPT_POSTFIELDS, which means that the values ​​passed with @ can be transmitted securely as fields. Instead of a prefix, you can use the option CURLFile d. Added in PHP 5.5.0 with default value FALSE. In PHP 5.6.0 it became equal to by default TRUE.
CURLOPT_SSL_VERIFYPEER FALSE to stop cURL from checking the host certificate. Alternative certificates to be verified can be specified using the parameter CURLOPT_CAINFO or the directory with certificates specified by the parameter CURLOPT_CAPATH. Default is TRUE since cURL version 7.10. The default distribution is installed starting from cURL version 7.10.
CURLOPT_TRANSFERTEXT TRUE to use ASCII mode for FTP transfers. When using LDAP, the data is returned in plain text instead of HTML. On Windows systems the thread STDOUT does not set to binary mode.
CURLOPT_UNRESTRICTED_AUTH TRUE to continue sending login and password during redirects (when using CURLOPT_FOLLOWLOCATION), even if the hostname changes.
CURLOPT_UPLOAD TRUE to prepare for uploading the file to the server.
CURLOPT_VERBOSE TRUE to display additional information. Writes output to a stream STDERR, or the file specified by the parameter CURLOPT_STDERR.

For the following option parameter values, the value parameter must be of type integer:

Parameter Set value value Notes
CURLOPT_BUFFERSIZE The size of the buffer used for each read. However, there is no guarantee that this request will be completed. Added in cURL 7.10.
CURLOPT_CLOSEPOLICY One of the constants CURLCLOSEPOLICY_*.

Comment:

This option is deprecated as it was never implemented in cURL and did not work.

Removed in PHP 5.6.0.
CURLOPT_CONNECTTIMEOUT The number of seconds to wait when trying to connect. Use 0 to wait indefinitely.
CURLOPT_CONNECTTIMEOUT_MS The number of milliseconds to wait when attempting to connect. Use 0 to wait indefinitely. If libcurl is compiled using the system's standard name resolver, then the connection will still use a full second wait as a timeout, with a minimum allowed timeout of 1 second. Added in cURL version 7.16.2. Available starting from PHP 5.2.3.
CURLOPT_DNS_CACHE_TIMEOUT The number of seconds that DNS records are stored in memory. By default, this parameter is 120 (2 minutes).
CURLOPT_FTPSSLAUTH FTP authentication method (in active mode): CURLFTPAUTH_SSL(SSL is checked first), CURLFTPAUTH_TLS(TLS checked first) or CURLFTPAUTH_DEFAULT(cURL decides for itself). Added in cURL version 7.12.2.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (by default, CURL chooses which version to use), CURL_HTTP_VERSION_1_0 (force HTTP/1.0), or CURL_HTTP_VERSION_1_1 (force HTTP/1.1).
CURLOPT_HTTPAUTH

You can use the bitwise operator | (or) to combine several methods together. In this case, cURL will poll the server for supported authorization methods and select the best one.

CURLAUTH_ANY is an alias CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLOPT_INFILESIZE The expected file size, in bytes, when uploading a file to a remote server. Please note that using this option will not stop further data being sent in excess of this value, as the data sent depends on the result CURLOPT_READFUNCTION.
CURLOPT_LOW_SPEED_LIMIT Upper threshold for data transfer rate, in bytes per second. The verification takes place within CURLOPT_LOW_SPEED_TIME seconds, after which PHP considers the transfer too slow and aborts it.
CURLOPT_LOW_SPEED_TIME The maximum number of seconds during which the transfer rate must not exceed CURLOPT_LOW_SPEED_LIMIT, otherwise PHP will mark the transfer as too slow and stop it.
CURLOPT_MAXCONNECTS Maximum number of persistent connections. When the limit is reached, the parameter is used to determine which connection to close. CURLOPT_CLOSEPOLICY.
CURLOPT_MAXREDIRS The maximum number of accepted redirects. Use this option together with the option CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT Alternative connection port.
CURLOPT_POSTREDIR A bit mask containing 1 (301 Moved Permanently), 2 (302 Found) and 4 (303 See Other) to specify whether the HTTP POST method should be processed when the option is enabled CURLOPT_FOLLOWLOCATION if the specified type of redirection occurred. Added in cURL 7.19.1. Available since PHP 5.3.2.
CURLOPT_PROTOCOLS

Bit mask of values CURLPROTO_*. This mask limits the protocols used by libcurl. This allows you to have libcurl work with a large number of protocols, and limit the operation of certain transfers to only a subset of them. By default, libcurl uses all supported protocols. See also parameter CURLOPT_REDIR_PROTOCOLS.

Correct protocol values: CURLPROTO_HTTP , CURLPROTO_HTTPS , CURLPROTO_FTP , CURLPROTO_FTPS , CURLPROTO_SCP , CURLPROTO_SFTP , CURLPROTO_TELNET , CURLPROTO_LDAP , CURLPROTO_LDAPS , CURLPROTO_DICT , CURLPROTO_FILE , C URLPROTO_TFTP, CURLPROTO_ALL

CURLOPT_PROXYAUTH HTTP authorization methods used when connecting to a proxy server. Use the same bit masks that were described for the parameter CURLOPT_HTTPAUTH. Currently, only CURLAUTH_BASIC and CURLAUTH_NTLM are supported for proxy authorization. Added in cURL version 7.10.7.
CURLOPT_PROXYPORT The port number of the proxy server to which the connection is made. This number can also be set using the parameter CURLOPT_PROXY.
CURLOPT_PROXYTYPE Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5 . Added in cURL 7.10.
CURLOPT_REDIR_PROTOCOLS Bit mask of values CURLPROTO_*. This bitmask limits the protocols used by libcurl when redirecting (with the parameter enabled CURLOPT_FOLLOWLOCATION). This allows you to limit the set of protocols used when redirecting for some transfers. By default, libcurl supports all protocols except FILE and SCP. In versions prior to 7.19.4, redirection was used for all protocols without exception. See also parameter description CURLOPT_PROTOCOLS for a list of constants with protocol values. Added in cURL version 7.19.4.
CURLOPT_RESUME_FROM Transmission start offset, in bytes.
CURLOPT_SSL_VERIFYHOST Use 1 to check for the existence of a common name in the SSL certificate. Use 2 to check that the common name exists and also matches the specified host. In a combat environment, the value of this parameter should be 2 (set by default). Support for value 1 has been removed in cURL 7.28.1
CURLOPT_SSLVERSION One of the constants CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1(5) or CURL_SSLVERSION_TLSv1_2 (6).
CURLOPT_TIMECONDITION Parameter interpretation method CURLOPT_TIMEVALUE. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has changed since the time specified in the parameter CURLOPT_TIMEVALUE. If the page has not been modified, the title will be returned "304 Not Modified", implying that the parameter CURLOPT_HEADER installed in TRUE. Use CURL_TIMECOND_IFUNMODSINCE for the opposite effect. The default is CURL_TIMECOND_IFMODSINCE.
CURLOPT_TIMEOUT The maximum number of seconds allowed for executing cURL functions.
CURLOPT_TIMEOUT_MS The maximum number of milliseconds allowed for executing cURL functions. If libcurl is built using the normal system name resolver, then this connection span will still use second rounding timeouts, with a minimum timeout allowed of one second. Added in cURL version 7.16.2. Available starting from PHP 5.2.3.
CURLOPT_TIMEVALUE Number of seconds since January 1, 1970. This time will be used by the parameter CURLOPT_TIMECONDITION. By default, the CURL_TIMECOND_IFMODSINCE parameter is used.
CURLOPT_MAX_RECV_SPEED_LARGE If the download speed exceeds this value (specified in bytes per second) on average over the entire transfer, the download will be paused to maintain the average speed less than or equal to this parameter. By default, the speed is not limited.
CURLOPT_MAX_SEND_SPEED_LARGE If the upload to the server exceeds this value (specified in bytes per second) on average throughout the entire transfer, the upload will be paused to maintain an average speed less than or equal to this parameter. By default, the speed is not limited. Added in cURL 7.15.5. Available starting from PHP 5.4.0.
CURLOPT_SSH_AUTH_TYPES A bitmask consisting of one or more constants: CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. Install CURLSSH_AUTH_ANY in order for libcurl to choose one of them independently. Added in cURL 7.16.1.
CURLOPT_IPRESOLVE Allows an application to select the type of IP address with which the hostname is determined. This is necessary if you are using a hostname that is derived from more than one version of the IP address. Possible values ​​could be CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6, and by default CURL_IPRESOLVE_WHATEVER. Added in cURL 7.10.8.

For the following option parameter values, the value parameter must be of type string:

Parameter Set value value Notes
CURLOPT_CAINFO The name of a file containing one or more certificates against which nodes will be checked. This parameter only makes sense when used in conjunction with CURLOPT_SSL_VERIFYPEER. Requires an absolute path.
CURLOPT_CAPATH A directory containing several CA certificates. Use this option in conjunction with CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE Header content "Cookie:", used in the HTTP request. Please note that multiple cookies are separated by a semicolon followed by a space (for example, " fruit=apple; color=red")
CURLOPT_COOKIEFILE The name of the file containing the cookies. This file must be in Netscape format or simply HTTP headers written to the file. If an empty string is passed as the file name, then cookies will not be saved, but their processing will still be enabled.
CURLOPT_COOKIEJAR The name of the file in which all internal cookies of the current transfer will be saved after the handle is closed, for example after calling curl_close.
CURLOPT_CUSTOMREQUEST

Custom request method used instead "GET" or "HEAD" when making an HTTP request. This is useful for queries "DELETE" or other, more rare HTTP requests. Correct meanings would be words like "GET", "POST", "CONNECT" and so on; those. Do not enter the entire HTTP request line here. For example, an indication "GET /index.html HTTP/1.0\r\n\r\n" will be wrong.

Comment:

Do not use this feature until you are sure that the server supports this type of request.

CURLOPT_EGDSOCKET Like CURLOPT_RANDOM_FILE, except that the filename is set to the Entropy Gathering Daemon socket.
CURLOPT_ENCODING Header content "Accept-Encoding: ". This allows the request to be decoded. Supported encodings are "identity", "deflate" And "gzip". If an empty string is passed, "" , a header containing all supported encoding types is sent. Added in cURL 7.10.
CURLOPT_FTPPORT The value that will be used to determine the IP address for the FTP "PORT" command. The "PORT" command tells the server which IP address it should connect to. This can be an IP address, hostname, network interface name (under Unix), or simply "-" to use the default system IP address.
CURLOPT_INTERFACE The name of the network interface to use. Can be an interface name, an IP address, or a host name.
CURLOPT_KEYPASSWD Password required to use the private key CURLOPT_SSLKEY or CURLOPT_SSH_PRIVATE_KEYFILE. Added in cURL 7.16.1.
CURLOPT_KRB4LEVEL Security level KRB4 (Kerberos 4). Any of the following values ​​(in order from weakest to strongest) are correct: "clear", "safe", "confidential", "private".. If the specified string differs from the given values, the value will be used "private". Setting this option to NULL will completely disable KRB4 security. At the moment, KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDS All data transmitted in an HTTP POST request. To transfer a file, specify before the file name @ , and also use the full path to the file. The file type can also be specified using the format " ;type=mimetype" following the file name. This parameter can be passed as a url-encoded string, like " para1=val1¶2=val2&...", and in the form of an array, the keys of which will be the names of the fields, and the values ​​will be their contents. If value is an array, the header Content-Type will be set to multipart/form-data. Starting from PHP 5.2.0, when transferring files with the prefix @ , value must be an array. Since PHP 5.5.0, prefix @ is deprecated and files can be sent using CURLFile. Prefix @ can be disabled to allow values ​​starting with @ by setting the option CURLOPT_SAFE_UPLOAD in meaning TRUE.
CURLOPT_PROXY HTTP proxy through which requests will be routed.
CURLOPT_PROXYUSERPWD Login and password written in the form ":" , used when connecting through a proxy.
CURLOPT_RANDOM_FILE The name of the file used to initialize the random number generator for SSL.
CURLOPT_RANGE Range of data to be downloaded, in format "X-Y", and either X or Y can be omitted. The HTTP protocol also supports the transmission of multiple ranges separated by commas, they are specified in the format "X-Y,N-M".
CURLOPT_REFERER Header content "Referrer:", which will be used in the HTTP request.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 A string containing 32 hexadecimal digits. The string must be an MD5 checksum of the remote computer's public key, and libcurl will reset the connection to the remote host until the checksum matches the public key. This option is only for transferring data using SCP and SFTP. Added in cURL 7.17.1.
CURLOPT_SSH_PUBLIC_KEYFILE The file name for your public key. If not specified, libcurl defaults to the file $HOME/.ssh/id_dsa.pub if the HOME environment variable is set and the file "id_dsa.pub" in the current directory if the HOME environment variable is not set. Added in cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE The file name for your private key. If not specified, libcurl defaults to the $HOME/.ssh/id_dsa file if the HOME environment variable is set and the "id_dsa" file in the current directory if the HOME environment variable is not set. If the file is password protected, set the password using CURLOPT_KEYPASSWD. Added in cURL 7.16.1.
CURLOPT_SSL_CIPHER_LIST List of ciphers used in SSL transfers. For example, RC4-SHA And TLSv1 are valid cipher lists.
CURLOPT_SSLCERT The name of a file with a correctly formatted PEM certificate.
CURLOPT_SSLCERTPASSWD Password required to use the certificate CURLOPT_SSLCERT.
CURLOPT_SSLCERTTYPE Certificate format. Formats supported "PEM"(default), "DER" And "ENG". Added in cURL version 7.9.3.
CURLOPT_SSLENGINE The encryption engine ID for the SSL private key specified in the parameter CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT The identifier of the encryption mechanism used for asymmetric encryption operations.
CURLOPT_SSLKEY The name of the SSL private key file.
CURLOPT_SSLKEYPASSWD

The secret password required to use the SSL private key specified by the parameter CURLOPT_SSLKEY.

Comment:

Since this parameter contains a valuable password, remember to keep this PHP script in a safe place.

CURLOPT_SSLKEYTYPE The type of SSL private key specified in the parameter CURLOPT_SSLKEY. The following key types are supported: "PEM"(default), "DER" And "ENG".
CURLOPT_URL Downloadable URL. This parameter can also be set when initializing a session using curl_init().
CURLOPT_USERAGENT Header content "User-Agent: ", sent in an HTTP request.
CURLOPT_USERPWD Login and password used during connection, specified in the format ":" .

For the following option parameter values, the value parameter must be an array:

Parameter Set value value Notes
CURLOPT_HTTP200ALIASES An array of HTTP 200 responses that will be treated as correct responses rather than erroneous ones. Added in cURL version 7.10.3.
CURLOPT_HTTPHEADER An array of set HTTP headers, in the format array("Content-type: text/plain", "Content-length: 100")
CURLOPT_POSTQUOTE An array of FTP commands executed on the server after an FTP request is completed.
CURLOPT_QUOTE An array of FTP commands executed on the server before making an FTP request.

For the following option parameter values, the value parameter must be a stream handle (returned, for example, by the function fopen()):

Parameter Set value value
CURLOPT_FILE The file in which the transfer result will be written. Default output stream STDOUT(browser window).
CURLOPT_INFILE The file from which data should be read when uploaded to the server.
CURLOPT_STDERR Alternative error output file used in place of the error stream STDERR.
CURLOPT_WRITEHEADER The file in which the headers of the current operation will be written.

For the following option parameter values, the value parameter must be a valid function name or closure:

Parameter Set value value
CURLOPT_HEADERFUNCTION The callback function takes two parameters. The first parameter is the cURL handle, the second parameter is a string containing the headers to be written. Headers must be written using this callback function. Should return the number of bytes written.
CURLOPT_PASSWDFUNCTION The callback function takes three parameters. The first parameter is the cURL handle, the second parameter is the password prompt string, and the third parameter is the maximum password length. Should return a string containing the password.
CURLOPT_PROGRESSFUNCTION

The callback function takes five parameters. The first is the cURL descriptor, the second is the total number of bytes expected to be downloaded from the server, the third is the number of bytes already downloaded, the fourth is the total number of bytes expected to be sent to the server, and the fifth is the number of bytes already sent.

Comment:

The callback function is called only if the option CURLOPT_NOPROGRESS set to value FALSE.

You can return a non-zero value to cancel the transfer. In this case an error will be displayed CURLE_ABORTED_BY_CALLBACK.

CURLOPT_READFUNCTION The callback function takes three parameters. The first parameter is the cURL handle, the second parameter is the stream resource passed to cURL via the option CURLOPT_INFILE, and the third parameter is the maximum allowed amount of data to be read. The callback function must return a string of length no greater than the requested amount of data, usually by reading from the passed streaming resource. Should return an empty string to signal the end of the file EOF.
CURLOPT_WRITEFUNCTION The callback function takes two parameters. The first parameter is the cURL handle, and the second parameter is the string containing the data to be written. Data must be saved using this function. It must return the exact number of bytes written, otherwise the download will be aborted with an error.

Other meanings:

Return values

Returns TRUE upon successful completion or FALSE in case of an error.

List of changes

Version Description
5.6.0 Option CURL_SAFE_UPLOAD now has a default value of TRUE.
5.6.0 Removed option CURLOPT_CLOSEPOLICY and its associated meanings.
5.5.0 The cURL resource is added as the first argument to the callback function CURLOPT_PROGRESSFUNCTION.
5.5.0 Added option CURLOPT_SHARE.
5.3.0 Added option CURLOPT_PROGRESSFUNCTION.
5.2.10 Added options CURLOPT_PROTOCOLS And CURLOPT_REDIR_PROTOCOLS.
5.1.0 Added options CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH And CURLOPT_TIMECONDITION.
5.0.0 Added options CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE And CURLOPT_HTTP200ALIASES.

Examples

Example #1 Initializing a CURL session and loading a web page

// create a new cURL resource
$ch = curl_init();

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array("name" => "Foo" , "file" => "@/home/user/test.png" );

Curl_setopt($ch, CURLOPT_URL, "http://localhost/upload.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Curl_exec($ch);
?>

The result of running this example:

Array ( => Foo) Array ( => Array ( => test.png => image/png => /tmp/phpcpjNeQ => 0 => 279))

Notes

Comment:

Passing an array to CURLOPT_POSTFIELDS encodes the data as multipart/form-data, whereas passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.