Skip to content

Send files via cURL in PHP 5.5+

Last updated on November 18, 2022

In this post, I would like to show you file uploading via cURL. cURL is a great glaring library. It can be used to make HTTP requests to remote servers like a normal web browser and we can also send files to the server using cURL as browsers do.

This example will only work with PHP 5.5+ version. Because I am using CurlFile() class API for uploading files.CurlFile() is an improved version of our previous(special value: @ before file path) cURl file upload method.

Old way :

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

$ch = curl_init();

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_URL, 'http://example.com/upload.php');

$postData = array(
    'file' => '@/path/to/file.txt',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$response = curl_exec($ch);

/* 
 http://example.com/upload.php:
*/

The file path must be an absolute path rather than a path relative to the current directory. You can use realpath() function to get the real path of the file.

The right way – Secure way

Instead of using the above method, the following should be used to upload files with CURLOPT_POSTFIELDS. The following code makes a request to http://example.com/upload.php, uploads the file file.txt, and outputs the response.

$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);

/*
 http://example.com/upload.php:
*/

Syntax :

public CURLFile::__construct ( string $filename [, string $mimetype [, string $postname ]] )
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments