fck2ta
Last Updated: March 02, 2016
·
26.54K
· hobnob
Dave

How to send files via cURL in PHP

If you need to upload a file to a service using cURL, just append an at symbol (@) to a string containing the file path.

For example:

//Initialise the cURL var
$ch = curl_init();

//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Set the Url
curl_setopt($ch, CURLOPT_URL, 'http://www.example.org/');

//Create a POST array with the file in it
$postData = array(
    'testData' => '@/path/to/file.txt',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

// Execute the request
$response = curl_exec($ch);

This will send the contents of /path/to/file.txt up to example.org
The important part of the above code is

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

5 Responses
Add your response

10695

hi, im trying this :

$ch = curlinit();
curl
setopt($ch, CURLOPTRETURNTRANSFER, 1);
$data = array('name' => 'Foo', 'file' => '@my-event-name.ics');
curl
setopt($ch, CURLOPTURL, 'http://icalx.com/public/zeroan/');
curl
setopt($ch, CURLOPTPOST, 1);
curl
setopt($ch,CURLOPTUSERPWD,'zeroan:pass');
curl
setopt($ch, CURLOPTPOSTFIELDS, $data);
$data2=curl
exec($ch);

but its not uploading =( can you help me?

over 1 year ago ·
10696
Dave

Hi,

I can't see anything initially wrong here. Have you tried setting an absolute path to the file rather than a relative one?

over 1 year ago ·
10699

Nothing, i guess the website is the problem =(. Thank you

over 1 year ago ·
14597
Photo

I think it won't work because "As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile." is written in PHP Manual

http://www.php.net/manual/en/function.curl-setopt.php

Thanks.

over 1 year ago ·
22323
None

@ prefix is deprecated. If you are on php 5.5. you can use CURLFile class or curlfilecreate function.

This lib does it: https://github.com/phplicengine/phplicengine-api

over 1 year ago ·