MQL4 login to a webpage translate from php request

 

Hello everyone,

I am trying to login to my webpage using mql4. My friend have said that my website uses tricky system with some hash number.

I know nothing about server communication so he has provided me a PHP code which logins successfully. Can somebody explain how to transfer it to mql4? Or maybe more detailed Webrequest() guide because the default from mt4 is very poor and extremely lacks information...

 

// step 1) load login page
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.yesfx.com.cy/index");
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$output = curl_exec($ch);
curl_close($ch);
 
// ... read the generated CSRF token
$csrf = null;
if (preg_match('/name="([a-zA-Z0-9]{32})" value="1"/', $output, $m)) {
    $csrf = $m[1];
} else {
    die("CSRF token not found");
}
 
// step 2) do a login request using the CSRF token
$post = array(
    'username' => 'testeraccount',
    'password' => 'aspirin',
    'view' => 'user',
    'task' => 'login',
    'submit' => 'Login',
    $csrf => '1',
);
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.yesfx.com.cy/forum");
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
 
// ... this will always return 303, no matter if the username/password works or not
$output = curl_exec($ch);
curl_close($ch);
 
// step 3) check we are logged or not (could be replaced by FOLLOW REDIRECT settings in the login POST above)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.yesfx.com.cy/index");
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
 
$output = curl_exec($ch);
$header = substr($output, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
curl_close($ch);
 
if (strpos($header, "X-Logged-In: True") !== false) {
    die("Logged in!");
} else if (strpos($header, "X-Logged-In: False") !== false) {
    die("Username/password error");
} else {
    die("Logged-in header not found");
}
 
No one knows how to login with csrf token?
 
Georgiy Liashchenko:
No one knows how to login with csrf token?
CSRF is just an additional data field unique for every request, which is provided in a server response for its client and should be passed back to the server during next request. If you do already have an mql code with WebRequest, you should parse the outcome (the login page html) and extract CSRF value using mql (analogue of preg_match). You can find more details here. Then use extracted value in next WebRequest payload.
 
Stanislav Korotky:
CSRF is just an additional data field unique for every request, which is provided in a server response for its client and should be passed back to the server during next request. If you do already have an mql code with WebRequest, you should parse the outcome (the login page html) and extract CSRF value using mql (analogue of preg_match). You can find more details here. Then use extracted value in next WebRequest payload.

Thanks, question now is how to form a post request.

Currently i use

   string str="Login="+Login+"&Password="+Password+"&CSRF="+csrf;
   ArrayResize(data,StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8)-1);
   res=WebRequest("POST",authurl,NULL,0,data,data,str);

 But no result :(

 
please paste full code, not just a part
 
Aleksei Beliakov:
please paste full code, not just a part
//+------------------------------------------------------------------+
bool Authorization(string csrf)
  {
   int    res;     // To receive the operation execution result
   char   data[];  // Data array to send POST requests
   string authurl="http://www.yesfx.com.cy/index";
   string str="Login="+Login+"&Password="+Password+"&csrf="+csrf;

   ArrayResize(data,StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8)-1);
   ResetLastError();
   res=WebRequest("POST",authurl,NULL,0,data,data,str);
   
   Print(csrf);
   Print(res);
   Alert(str);
   if(GetLastError()==4060)
     {
      Alert("You have not added ",authurl," to URL permition list in the ( Tools > Options > Expert Advisors tab )");
     }
   if(res!=200)
     {
      Print("Authorization failed! Please contact your seller, LastError="+(string)res);
      return(false);
     }

   return(true);
  }

//+------------------------------------------------------------------+
void OnStart()
  {
//---
   string cookie=NULL,headers,fstr;
   char post[],result[];
   int res;

   string page_url="http://www.yesfx.com.cy/index";
   ResetLastError();
   int timeout=10000; //--- Timeout below 1000 (1 sec.) is not enough for slow Internet connection 
   res=WebRequest("GET",page_url,cookie,NULL,timeout,post,0,result,headers);
//--- Checking errors 
   if(res==-1)
     {
      Print("Error in WebRequest. Error code  =",GetLastError());
      //--- Perhaps the URL is not listed, display a message about the necessity to add the address 
      MessageBox("Add the address '"+page_url+"' in the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
     }
   else
     {
      //--- Save the data to a file 
      int filehandle=FileOpen("yesfx.htm",FILE_WRITE|FILE_BIN);
      //--- Checking errors 
      if(filehandle!=INVALID_HANDLE)
        {
         //--- Save the contents of the result[] array to a file 
         FileWriteArray(filehandle,result,0,ArraySize(result));
         //--- Close the file 
         FileClose(filehandle);
        }
      else Print("Error in FileOpen. Error code=",GetLastError());

      filehandle=FileOpen("yesfx.htm",FILE_READ|FILE_BIN);
      //--- Checking errors 
      if(filehandle!=INVALID_HANDLE)
        {
         //--- Read the contents of the result[] array to a file 
         fstr=FileReadString(filehandle,(int)FileSize(filehandle));
         fstr=StringSubstr(fstr,StringFind(fstr,"user",5000)+84,32);
         //--- Close the file 
         FileClose(filehandle);
        }
      else Print("Error in FileOpen. Error code=",GetLastError());

     }
   Authorization(fstr);
  }
//+------------------------------------------------------------------+
 
You may find more details on the russian forum.

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

Как авторизоваться через WebRequest?

Rashid Umarov, 2015.01.12 16:08

В новом билде будет доступна расширенная версия функции WebRequest(). Вот  пример авторизации на сайте mql5.com и послледующей публикации поста в ленте пользователя.

//+------------------------------------------------------------------+
//|                                                   WebRequest.mq5 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property link      "http://www.mql5.com"
#property version   "1.00"
#property strict
#property script_show_inputs
#property description "Пример скрипта, который публикует сообщение "
#property description "пользователя в ленте на mql5.com"

input string InpLogin   ="";             //Ваш аккаунт в MQL5.com
input string InpPassword="";             //Пароль для вашего аккаунта
input string InpFileName="EURUSDM5.png"; //Картинка в папке MQL5/Files/
input string InpFileType="image/png";    //Правильный mime type картинки
//+------------------------------------------------------------------+
//| Публикация сообщения с картинкой в ленте mql5.com                |
//+------------------------------------------------------------------+
bool PostToNewsFeed(string login,string password,string text,string filename,string filetype)
  {
   int    res;     // для помещения результата выполнения операций
   char   data[];  // массив с данными для отправки POST-запросов
   char   file[];  // сюда прочитаем картинку
   string str="Login="+login+"&Password="+password;
   string auth,sep="-------Jyecslin9mp8RdKV"; // разделитель данных формата multipart
//--- имеется файл - пробуем прочитать его
   if(filename!=NULL && filename!="")
     {
      res=FileOpen(filename,FILE_READ|FILE_BIN);
      if(res<0)
        {
         Print("Ошибка открытия файла \""+filename+"\"");
         return(false);
        }
      //--- читаем данные файла
      if(FileReadArray(res,file)!=FileSize(res))
        {
         FileClose(res);
         Print("Ошибка чтения файла \""+filename+"\"");
         return(false);
        }
      //---
      FileClose(res);
     }
//--- сформируем тело POST запроса на авторизацию
   ArrayResize(data,StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8)-1);
//--- сбросим код ошибки
   ResetLastError();
//--- выполняем запрос на автиризацию
   res=WebRequest("POST","https://www.mql5.com/ru/auth_login",NULL,0,data,data,str);
//--- если авторизация не удалась
   if(res!=200)
     {
      Print("Ошибка авторизации #"+(string)res+", LastError="+(string)GetLastError());
      return(false);
     }
//--- вычитаем из заголовка ответа сервера авторизационную куку
   res=StringFind(str,"Set-Cookie: auth=");
//--- если кука не найдена - сообщим об ошибке
   if(res<0)
     {
      Print("Ошибка, данные авторизации не найдены в ответе сервера (проверте логин/пароль)");
      return(false);
     }
//--- запомним авторизационные данные и сформируем заголовок для последующих запросов
   auth=StringSubstr(str,res+12);
   auth="Cookie: "+StringSubstr(auth,0,StringFind(auth,";")+1)+"\r\n";
//--- если имеется файл данных - отправляем его на сервер
   if(ArraySize(file)!=0)
     {
      //--- сформируем тело запроса
      str="--"+sep+"\r\n";
      str+="Content-Disposition: form-data; name=\"attachedFile_imagesLoader\"; filename=\""+filename+"\"\r\n";
      str+="Content-Type: "+filetype+"\r\n\r\n";
      res =StringToCharArray(str,data);
      res+=ArrayCopy(data,file,res-1,0);
      res+=StringToCharArray("\r\n--"+sep+"--\r\n",data,res-1);
      ArrayResize(data,ArraySize(data)-1);
      //--- сформируем заголовок запроса
      str=auth+"Content-Type: multipart/form-data; boundary="+sep+"\r\n";
      //--- сбросим код ошибки
      ResetLastError();
      //--- выполняем запрос на передачу файла изображения на сервер
      res=WebRequest("POST","https://www.mql5.com/upload_file",str,0,data,data,str);
      //--- проверим результат запроса
      if(res!=200)
        {
         Print("Ошибка передачи файла на сервер #"+(string)res+", LastError="+(string)GetLastError());
         return(false);
        }
      //--- получим ссылку на картинку, которую загрузили на сервер
      str=CharArrayToString(data);
      if(StringFind(str,"{\"Url\":\"")==0)
        {
         res     =StringFind(str,"\"",8);
         filename=StringSubstr(str,8,res-8);
         //--- при ошибке закачки файла, вернётся пустая ссылка
         if(filename=="")
           {
            Print("Передача файла на сервер не удалась");
            return(false);
           }
        }
     }
//--- сформируем тело запроса публикации сообщения на сервере
   str ="--"+sep+"\r\n";
   str+="Content-Disposition: form-data; name=\"content\"\r\n\r\n";
   str+=text+"\r\n";
//--- на каких языках сайта mql5.com будет доступна публикация 
   str+="--"+sep+"\r\n";
   str+="Content-Disposition: form-data; name=\"AllLanguages\"\r\n\r\n";
   str+="on\r\n";
//--- если картинка была загружена на сервер - передадим ссылку на неё
   if(ArraySize(file)!=0)
     {
      str+="--"+sep+"\r\n";
      str+="Content-Disposition: form-data; name=\"attachedImage_0\"\r\n\r\n";
      str+=filename+"\r\n";
     }
//--- завершающая строка multipart-запроса
   str+="--"+sep+"--\r\n";
//--- собираем тело POST-запроса в одну строку 
   StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8);
   ArrayResize(data,ArraySize(data)-1);
//--- подготовим заголовок запроса   
   str=auth+"Content-Type: multipart/form-data; boundary="+sep+"\r\n";
//--- выполняем запрос на публикацию сообщение в ленте пользователя mql5.com
   res=WebRequest("POST","https://www.mql5.com/ru/users/"+login+"/wall",str,0,data,data,str);
//--- в случае успешной публикации вернем true
   return(res==200);
  }
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- опубликуем пост на mql5.com c картинкой, путь к которой возьмем из параметра InpFileName
   PostToNewsFeed(InpLogin,InpPassword,"Проверка расширенной версии функции WebRequest\r\n"
                  "(Данное сообщение размещено скриптом WebRequest.mq5)",InpFileName,InpFileType);
  }
//+------------------------------------------------------------------+

 
Stanislav Korotky:
You may find more details on the russian forum.

i have figured out that the post must be the following 

string str="view=user&task=login&"+csrf+"=1&username="+Login+"&password="+Password+"&submit=Login";

 but still the same result, maybe some headers or cookies has to be sent back as well?

 
Georgiy Liashchenko:

i have figured out that the post must be the following 

 but still the same result, maybe some headers or cookies has to be sent back as well?

Open developer tools in some browser and investigate all requests/responses made during login. The site may look at cookies, referrer and other stuff (such as HTML5 storage), which you can't support using MQL.
Reason: