cURL GET request function is not returning a string

时间:2017-11-13 06:07:53

标签: php c++ curl libcurl

I am writing a program in OS X which requires to run the users HWID through a PHP script, which will then echo a value which will be read using a function in my code.

This PHP script, basically checks the IP that the GET request was made from, checks if the IP exists in a table, if it does, then check for other values such as if the given HWID is correct, or if the user is premium and then returns a string according to this.

This is the function here;

string pullResult(string hwid) {
    CURL* curl;
    string result;

    curl = curl_easy_init();
    std::string url = "removed/usercheck.php?hwid=" + hwid;
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    result = curl_easy_perform(curl);

    return result;
}

And this is where it is called;

if(al.pullResult(hwid) == "no such user")
    cout << "no such user" << endl;

However, using this function does not work. I can go into my browser and make the GET request and the script returns the right strings, but this just doesn't return the string.

Now, I know for a fact I am checking for the right string as I have everything setup for this string to be the outcome.

EDIT: I've actually read the manual now, lol, and found out that this won't return a string or what is read from the webpage, rather it's own flag-ish thing. If someone can tell me what I'm doing wrong in my function, that'd be great.

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西。它将指向std::string对象的指针传递给回调函数,该函数将返回的数据附加到传入的std::string中。错误检查的方式很少。在实际代码中,应检查每个函数调用的错误。

#include <memory>
#include <stdexcept>
#include <string>
#include <curl/curl.h>

std::size_t http_write(void* buf, std::size_t size, std::size_t nmemb, void* userp)
{
    if(auto page_data_ptr = static_cast<std::string*>(userp))
    {
        page_data_ptr->append(static_cast<char*>(buf), size * nmemb);
        return size * nmemb;
    }

    return 0;
}

std::string http_get(std::string const& url)
{
    // I use a unique_ptr to automatically call the cleanup function
    // so we don't need to do it later after the call
    std::unique_ptr<CURL, void(*)(CURL*)> curl{curl_easy_init(), curl_easy_cleanup};

    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &http_write);
    curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
    curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);

    std::string page_data; // collect the results
    curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &page_data);
    curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());

    CURLcode code = curl_easy_perform(curl.get());

    if(code != CURLE_OK)
        throw std::runtime_error(curl_easy_strerror(code));

    return page_data;
}

注意:在调用此功能之前,不要忘记拨打curl_global_init(CURL_GLOBAL_DEFAULT);