Last Updated: September 27, 2021
·
125.7K
· hobnob

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',
);

6 Responses
Add your response

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 ·

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 ·

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

over 1 year ago ·

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 ·

@ 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 ·

If you're using the curl functions directly in PHP, you're doing it wrong. The curl functions are extremely low-level, and are very easy to configure in an insecure way. You are better off, 99.9% of the time, using a fortified, professional-grade package like Guzzle that does everything right (securely) by default.

over 1 year ago ·