Rafael Ruiz Muñoz
Rafael Ruiz Muñoz

Reputation: 5472

Trying to upload a file from C++ with CURL to PHP

I'm trying to upload a picture (and its thumb) with CURL from C++ to my server.

The C++ doesn't present a problem by the moment, but the point is the following:

Immagine this is my code in PHP:

<?php
    $valid = $_GET['valid'];
    echo "hola";
    file_put_contents('queries.txt', "eh!\n");
?>

when I call my file.php it has to write a "queries.txt" in the same folder (and it does it).

Now, when calling if from C++, this is the code:

    string url = "http://myserver.com/file.php";

    CURL* curl = curl_easy_init();

    // set target url
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    // holders
    struct curl_httppost* beginPostList = NULL;
    struct curl_httppost* endPostList = NULL;

    string concat1 = tempFolder + imageName;
    string concat2 = tempFolder + image200Name;

    curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "image",
                 CURLFORM_FILE, &concat1, CURLFORM_END);
    curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "thumb",
                 CURLFORM_FILE, &concat2, CURLFORM_END);

    // perform
    curl_easy_setopt(curl, CURLOPT_POST, true);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, beginPostList);
    CURLcode code = curl_easy_perform(curl);

My current error is that the server isn't being called (because no "queries.txt" is being created), but if I remove this lines:

curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "image",
             CURLFORM_FILE, &concat1, CURLFORM_END);
curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "thumb",
             CURLFORM_FILE, &image200Name, CURLFORM_END);

the PHP script gets called perfectly. So, why CURL is not calling my script when adding any file?

Thank you in advance.


Edit:

1.- I've tried to call it by setting the content type:

curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "image",
             CURLFORM_FILE, &concat1,
             CURLFORM_CONTENTTYPE, "image/jpeg", CURLFORM_END);

but nothing happened


POSSIBLE ERROR:

I'm trying to not setting anything and I'm getting HTTP STATUS = 200, but if I set any file to upload, I get HTTP STATUS = 0... why?

Upvotes: 1

Views: 1055

Answers (1)

hlscalon
hlscalon

Reputation: 7552

You are passing a c++ string when it expects a c string

Try:

curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "image",
             CURLFORM_FILE, concat1.c_str(), CURLFORM_END);
curl_formadd(&beginPostList, &endPostList, CURLFORM_COPYNAME, "thumb",
             CURLFORM_FILE, concat2.c_str(), CURLFORM_END);

Upvotes: 2

Related Questions