如何检查cURL是否成功登录?c ++

How to check if cURL logged in succesfully? c++

本文关键字:登录 成功 是否 cURL 何检查 检查      更新时间:2023-10-16

所以我正在尝试制作一个 c++ 脚本,该脚本将登录到网站并将源代码输出到转储中.txt。 有没有办法确定脚本是否成功登录?

法典:

#include "pch.h"
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
CURL *curl;
CURLcode res;
FILE* logfile;
logfile = fopen("dump.txt" , "wb");
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0");
curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");`enter code here`
curl_easy_setopt(curl, CURLOPT_STDERR, logfile);
// Visit the login page once to obtain a PHPSESSID cookie
curl_easy_setopt(curl, CURLOPT_URL, "http://forum.nephrite.ro/index.php?app=core&module=global&section=login/");
curl_easy_perform(curl);

// Now, can actually login. First we forge the HTTP referer field, or HTS will deny the login
curl_easy_setopt(curl, CURLOPT_REFERER, "http://forum.nephrite.ro/index.php?app=core&module=global&section=login/");
// Next we tell LibCurl what HTTP POST data to submit
char data[] = "ips_username=xxx&ips_password=xxx";
char *ptrToString = data;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(logfile);
}
return 0;
}

使用 CURLOPT_WRITEFUNCTION & CURLOPT_WRITEDATA 捕获 curl 获取的页面,并检查它是否包含"登录成功"字符串,类似于

size_t curl_write_callback(const void * read_ptr, const size_t size,
const size_t count, void *s_ptr)
{
(*(string*) s_ptr).append((const char*) read_ptr, size * count);
return count;
}

然后

curl_easy_setopt(curl, CURLOPT_URL, "http://forum.nephrite.ro/index.php?app=core&module=global&section=login/");
string html;
curl_easy_setopt(curl,CURLOPT_WRITEDATA,&html);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,curl_write_callback);
curl_easy_perform(curl);
if(html.find_first_of("Welcome back Dave!")!=string::npos){
// login successful!
} else{
// login failed
}

只需将Welcome back Dave!替换为仅在登录成功时显示给您的一些字符串即可。 顺便说一下,在使用 C++ 时,不要使用 lambda 进行CURLOPT_WRITEFUNCTION,如果要使用类成员进行回调,类成员函数必须是静态的,否则很可能会遇到运行时崩溃。(去过那里,做过那>.<(