Send File to HTTPS URL using CURL and PHP

15,273

Solution 1

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);
?>

Solution 2

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.

Share:
15,273
Doug Molineux
Author by

Doug Molineux

I love programming in any language "Many developers have a mental block about their own fallibility" - Steve Townsend, Oct 4 2010

Updated on July 15, 2022

Comments

  • Doug Molineux
    Doug Molineux almost 2 years

    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

  • coreyward
    coreyward over 13 years
    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.
  • Admin
    Admin over 5 years
    How to use this for multiple files?