2

I am attempting to send a file to an Https URL with this code:

$file_to_upload = array('file_contents'=>'@'.$target_path); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $target_url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSER, FALSE);
curl_setopt($ch, CURLOPT_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, 'file='.$file_to_upload); 
$result = curl_exec($ch); 
$error = curl_error($ch);
curl_close ($ch); 
echo " Server response: ".$result; 
echo " Curl Error: ".$error;

But for some reason I'm getting this response:

Curl Error: Failed to open/read local data from file/application

Any advice would help thanks!

UPDATE: When I take out CURLOPT_UPLOAD, I get a response from the target server but it says that there was no file in the payload

2
  • You have confirmed $target_path is a valid and readable file? Commented Jan 20, 2011 at 18:38
  • I have yes, its octal is 775, owner apache Commented Jan 20, 2011 at 19:02

2 Answers 2

8

You're passing a rather strange argument to CURLOPT_POSTFIELDS. Try something more like:

<?
$postfields = array('file' => '@' . $target_path);
// ...
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
?>

Also, you probably want CURLOPT_RETURNTRANSFER to be true, otherwise $result won't get the output, it'll instead be sent directly to the buffer/browser.

This example from php.net might be of use as well:

<?php

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Once you hit a certain reputation level you can see the cumulative ups and downs that result in the overall score. I didn't know who downvoted, just that someone did. What are you wanting me to edit, by the way? Did I misstate something? I haven't seen any criticism.
How to use this for multiple files?
5

On top of coreward's answer:

According to how to upload file using curl with php, starting from php 5.5 you need to use curl_file_create($path) instead of "@$path".

Tested: it does work.

With the @ way no file gets uploaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.