Curl Basics and Using Curl from PHP

Curl on the command line

Based on the guide at http://www.ruanyifeng.com/blog/2011/09/curl.html.

  • Fetch page source: curl www.sina.com
  • Save to a file: curl -o <filename> www.sina.com
  • Follow redirects: curl -L www.sina.com
  • Show response with headers: curl -i www.sina.com
  • Show headers only: curl -I www.sina.com
  • Verbose output: curl -v www.sina.com
  • Even more detail: curl --trace output.txt www.sina.com
  • Send GET data: curl example.com/form.cgi?data=xxx
  • Send POST data: curl -X POST --data "data=xxx" example.com/form.cgi
  • URL-encode the POST body: curl -X POST --data-urlencode "date=April 1" example.com/form.cgi
  • Other verbs: curl -X DELETE www.example.com
  • Upload a file: curl --form upload=@localfilename --form press=OK <URL>
  • Set Referer: curl --referer http://www.example.com http://www.example.com
  • Set User-Agent: curl --user-agent "<User Agent>" <URL>
  • Send cookies: curl --cookie "name=xxx" www.example.com
  • Save cookies: curl -c cookies http://example.com
  • Load cookies from file: curl -b cookies http://example.com
  • Add custom headers: curl --header "Content-Type:application/json" http://example.com
  • Provide basic auth: curl --user name:password example.com

Curl from PHP

Reference: http://php.net/manual/zh/curl.examples-basic.php

The typical flow is: initialize a session with curl_init(), set options via curl_setopt(), execute with curl_exec(), and finally close the handle with curl_close(). Example: download the home page of example.com and save it to a file.

1
2
3
4
5
6
7
8
9
10
11
12
<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>