Sending files using cURL in PHP

The cURL functions in PHP can be used to make HTTP requests to remote servers. The curl_setopt function allows a wide range of options to be set, but none of these directly relate to sending files. Instead, files are sent using a special format for POST parameter values.

A simple example

The following code makes a request to http://example.com/, uploads the file example.txt, and outputs the response.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// initialise the curl request
$request = curl_init('http://example.com/');

// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    array(
      'file' => '@' . realpath('example.txt')
    ));

// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);

// close the session
curl_close($request);

Line 5 instructs cURL to perform a POST request. Lines 6 to 11 specify the array of POST parameters. On line 10, the POST parameter file is set to a special value: @, followed by the path to the file to send. The path must be an absolute path rather than a path relative to the current directory; in this example realpath is used to produce the absolute path.

Setting the file name

Note: the technique described in this section does not work in PHP versions 5.2.10 and lower. See PHP bug #48962 for details.

In addition to the file contents, the name of the file is sent in the request. An alternative file name can be specified by appending it to the parameter value as follows:

1
2
3
4
5
6
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    array(
      'file' => '@' . realpath('example.txt') . ';filename=name.txt'
    ));

Suppose a visitor uploads a file through a form; the file will be given a temporary name on the server, but when sending the file in a cURL request the original name should be sent. If the uploaded file’s details are in $_FILES['file'], the following code will send the original name:

1
2
3
4
5
6
7
8
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    array(
      'file' =>
          '@'            . $_FILES['file']['tmp_name']
          . ';filename=' . $_FILES['file']['name']
    ));

Setting the MIME type

Note: the technique described in this section does not work in PHP versions 5.2.6 and lower. See PHP bug #46696 for details.

The MIME type of the file sent in the cURL request can be specified in a similar way. Extending the previous example, the following code also sends the MIME type of the uploaded file:

1
2
3
4
5
6
7
8
9
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    array(
      'file' =>
          '@'            . $_FILES['file']['tmp_name']
          . ';filename=' . $_FILES['file']['name']
          . ';type='     . $_FILES['file']['type']
    ));

Where now?

Found this useful? Share it:

Also in PHP: