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',
);
Written by David North
Related protips
6 Responses
hi, im trying this :
$ch = curlinit();
curlsetopt($ch, CURLOPTRETURNTRANSFER, 1);
$data = array('name' => 'Foo', 'file' => '@my-event-name.ics');
curlsetopt($ch, CURLOPTURL, 'http://icalx.com/public/zeroan/');
curlsetopt($ch, CURLOPTPOST, 1);
curlsetopt($ch,CURLOPTUSERPWD,'zeroan:pass');
curlsetopt($ch, CURLOPTPOSTFIELDS, $data);
$data2=curlexec($ch);
but its not uploading =( can you help me?
Hi,
I can't see anything initially wrong here. Have you tried setting an absolute path to the file rather than a relative one?
Nothing, i guess the website is the problem =(. Thank you
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.
@ 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
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.