Failing to upload file with curl in heroku php app

2020-05-03 12:34发布

问题:

I'm getting the response "failed creating formpost data" from curl whenever I try to upload a file. I'm sensing from other posts on the web that it's the filepath that's wrong, but I can't seem to get an absolute path on heroku.

When i do dirname(__FILE__) all I get is /app/www/ that can't be right can it? How do I get the absolute file path in a heroku app?

this is my entire line for the image path to be included in post data

"@".dirname(__FILE__).'/images/wallimages/'.random_pic()

and my curl setup:

$ch = curl_init('https://url.com/'.$url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    if(curl_errno($ch))
    {
        return 'Curl error: ' . curl_error($ch);
    }
    curl_close ($ch);
    return $result;

回答1:

I suspect the root cause of your problem may be this line from the manual:

As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.

In any case, try this code and if it doesn't work, let me know what error message(s) you get so I can debug:

$uploadPath = rtrim(dirname(__FILE__),'/').'/images/wallimages/'.random_pic();
if (!is_file($uploadPath)) die("The file '$uploadPath' does not exist");
if (!is_readable($uploadPath)) die("The file '$uploadPath' is not readable");

$postFields = array (
  'nameOfFileControl' => "@$uploadPath",
  'someOtherFormControl' => 'some value'
  // Adjust this array to match your post fields.
  // Ensure you keep the array in this format!
);

$ch = curl_init('https://url.com/'.$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$result = curl_exec($ch);

if(curl_errno($ch))
{
    return 'Curl error: ' . curl_error($ch);
}
curl_close ($ch);
return $result;