Send File to HTTPS URL using CURL and PHP
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 targe开发者_C百科t server but it says that there was no file in the payload
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);
?>
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.
精彩评论