How to Upload a File using PHP cURL

Submitted on Jun 13, 2014, 8:14 p.m.

Here's how to upload/transfer a file server-to-server using PHP cURL (this is not a 'client' web form upload). The receiving server requires the top level key in the post data array to be 'file'. See the comments in the code.

1<?php
2
3// Helper function courtesy of https://github.com/guzzle/guzzle/blob/3a0787217e6c0246b457e637ddd33332efea1d2a/src/Guzzle/Http/Message/PostFile.php#L90
4function getCurlValue($filename, $contentType, $postname)
5{
6 // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
7 // See: https://wiki.php.net/rfc/curl-file-upload
8 if (function_exists('curl_file_create')) {
9 return curl_file_create($filename, $contentType, $postname);
10 }
11
12 // Use the old style if using an older version of PHP
13 $value = "@{$filename};filename=" . $postname;
14 if ($contentType) {
15 $value .= ';type=' . $contentType;
16 }
17
18 return $value;
19}
20
21$filename = '/path/to/file.jpg';
22$cfile = getCurlValue($filename,'image/jpeg','cattle-01.jpg');
23
24//NOTE: The top level key in the array is important, as some apis will insist that it is 'file'.
25$data = array('file' => $cfile);
26
27$ch = curl_init();
28$options = array(CURLOPT_URL => 'http://your/server/api/upload',
29 CURLOPT_RETURNTRANSFER => true,
30 CURLINFO_HEADER_OUT => true, //Request header
31 CURLOPT_HEADER => true, //Return header
32 CURLOPT_SSL_VERIFYPEER => false, //Don't veryify server certificate
33 CURLOPT_POST => true,
34 CURLOPT_POSTFIELDS => $data
35 );
36
37curl_setopt_array($ch, $options);
38$result = curl_exec($ch);
39$header_info = curl_getinfo($ch,CURLINFO_HEADER_OUT);
40$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
41$header = substr($result, 0, $header_size);
42$body = substr($result, $header_size);
43curl_close($ch);
44
45?>
46
47<!doctype html>
48<html>
49<head>
50 <meta charset="utf-8">
51 <title>File Upload results</title>
52</head>
53<body>
54 <p>Raw Result: <?=$result?>
55 <p>Header Sent: <?=$header_info?></p>
56 <p>Header Received: <?=$header?></p>
57 <p>Body: <?=$body?></p>
58</body>
59</html>