D
D
dllweb2016-10-23 22:15:55
PHP
dllweb, 2016-10-23 22:15:55

Authorization on instagram through curl, how?

Good time friends, the question is the following, how many times did not try to log in to Instagram through
PHP using CURL and it did not work out in the end. I do the following: I
create a request for the page - " https://www.instagram.com/accounts/login "
I immediately pull out the csrf token from there for the subsequent access of the completed form, send it, some kind of horror comes in response.
Below is the full code of the authorization attempt Please explain what is happening, what am I doing wrong?

<?php
function getCookie($str){
  
    
    // Парсинг кукисов
    $pattern_exec_cookie = "~Set-Cookie: (.*?);~ui";
    preg_match_all($pattern_exec_cookie, $str, $c);
    $cookie = "";
    foreach($c[0] as $rc){
      $cookie .= str_replace("Set-Cookie: ", "", $rc);
    }

    $cookie_array = explode(";", $cookie);
    $cookie_str = "";
    foreach($cookie_array as $ca){
      $ex = explode("=", $ca);
        if(isset($ex[1]) and !empty($ex[1]) and $ex[1] != '""'){
          $cookie_str .= $ex[0]."=".$ex[1]."; ";
        }
      }
    return trim($cookie_str);
}

$login = "login";
$passw = "PssWrd";

$user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)';
$url_auth = "https://www.instagram.com/accounts/login";
$url_auth_ajax = "https://www.instagram.com/accounts/login";

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_TIMEOUT, 30);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_HEADER, true);
      curl_setopt($ch, CURLINFO_HEADER_OUT, true);
      curl_setopt($ch, CURLOPT_URL, $url_auth);

      $curl_exec = curl_exec($ch);
      $bot_cookie = getCookie($curl_exec);

      curl_close($ch);

      $data = array(
      "username"=>$login,
      "password"=>$passw
      );
      
      $pattern = "~csrftoken=.*?;~ui";
      preg_match($pattern, $bot_cookie, $token);
      $ctoken = explode("=", str_replace(";", "", $token[0]));
      $csrf = $ctoken[1];
      
      
      $ch1 = curl_init();
      curl_setopt($ch1, CURLOPT_USERAGENT, $user_agent);
      curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch1, CURLOPT_NOBODY, 0);	
      curl_setopt($ch1, CURLOPT_COOKIE, $bot_cookie);
      curl_setopt($ch1, CURLOPT_TIMEOUT, 30);
      curl_setopt($ch1, CURLOPT_POST, true);
      curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch1, CURLOPT_HEADER, true);
      curl_setopt($ch1, CURLINFO_HEADER_OUT, true);
      curl_setopt($ch1, CURLOPT_HTTPHEADER, array(
      'authority: www.instagram.com',
      'method: POST',
      'path: /accounts/login/ajax/', 
      'scheme: https',
      'content-length: 44',
      'accept: */*',
      'accept-encoding: gzip, deflate, br',
      'accept-language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,und;q=0.2',
      'content-type: application/x-www-form-urlencoded',
      'cookie: s_network=; ig_pr=1; ig_vw=1920; '.$bot_cookie,
      'origin: https://www.instagram.com',
      'referer: https://www.instagram.com/',
      'user-agent: '.$user_agent,
      'x-csrftoken: '.$csrf,
      'x-instagram-ajax: 1',
      'x-requested-with: XMLHttpRequest')
      );
      curl_setopt($ch1, CURLOPT_URL, $url_auth_ajax);

      
      $result_auth = curl_exec($ch1);
      file_put_contents("insta_cookie.txt", $result_auth."\n", FILE_APPEND);
      $info = curl_getinfo($ch1);
      echo $result_auth;
      curl_close($ch1);
    
?>

You are welcome!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dllweb, 2016-10-23
@dllweb

Here is what comes in response to this request

HTTP/1.1 301 Moved Permanently
Strict-Transport-Security: max-age=86400
Content-Language: ru
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Vary: Accept-Language
Location: https://www.instagram.com/accounts/login/
Pragma: no-cache
Cache-Control: private, no-cache, no-store, must-revalidate
Date: Sun, 23 Oct 2016 19:13:49 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Content-Length: 0

HTTP/1.1 200 OK
Strict-Transport-Security: max-age=86400
Content-Language: ru
Content-Encoding: gzip
Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/; HttpOnly; Domain=instagram.com
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Vary: Cookie, Accept-Language, Accept-Encoding
Last-Modified: Sun, 23 Oct 2016 19:13:50 GMT
Pragma: no-cache
Cache-Control: private, no-cache, no-store, must-revalidate
Date: Sun, 23 Oct 2016 19:13:50 GMT
X-Frame-Options: SAMEORIGIN
Content-Type: text/html
Set-Cookie: csrftoken=egHsPjcba5OUj8G0XrYWXB6Q30vGlcyf; expires=Sun, 22-Oct-2017 19:13:50 GMT; Max-Age=31449600; Path=/; secure
Connection: keep-alive
Content-Length: 3307

‹ о
XяН[{sЫ6яЯџa;g№#Љ/‘"mЛm“жz™I—6Чvr9
H‚l`PІљж»Я¤mъE;ҐќV™XДcШэнж‡OѕщбЩПїэш­d‘н>1Н74C№D/ћЈЩЫ#¤?‡jе-зFU(Й±sѓqуXА\“’Ёщ
›Їb\љ9_.IjR†Њ#tшд
a)НЮљж…®ЊЏsoюбGтїгҐly«ЋЈ~Ж7p4НK\ЭN›GхiъDRСR"№-ЙЬђдTZЗxЌ›^гhCYК7“…¤eKЃжиЅ‘тв%З)ґЌ}ф
–dВшfґчбРjЁЋvОEDb”¬p%€њµММР8є2ј’І4Й»љ®зЖЇжлЇНgј(±¤qN`™њIВЂцЕу9I—Диr—Tждhз/+\мZmЧЕњюхБј_HьOтЊіЊ.Х5mRЙ‹э¶…P†љS"цћݲ⧴А&гkјПј1›ЋY0fіЭ·c=ыььp°saЏ3%D•М
ЛўgъВ—¤‰‰'ш®Т	#ТZ9-Ў°6$О@·Й±°{кIишУ(†¶qЛЉ[–u|q(д6'Эй‰zеЦи«њ&„	ўфю}·U–К$J,zZУ<E/ѕA®L#Я#Чv\УцLЧыЩхцн`ЯіM{jЫљѕaтуЉ LіЙ©ђ$EЂH№ў¤ бЉ QЗЗ$Їp"и9KСkA*фІ«НЧЛЉђњ?{ѕHҐ™MјХd`A%A|ГH5A_з9вР_ЎW|ҐD5¬Иi	hlQE„¬hўЛ*^ Z ђ5»Vxz¶|r'ќ…эЖkTа-в±Д°&ЊЦ8§)j-€°Ф\^їz)PLr€љЪ†AЛwэШ } ±Л•TKъW'и'Zp&8k(ЂЩѕЋЏ}ЛЪl6“b«›$ј°ф“U ‘hi¬.0­\сµ>зK+с’¬)Щ Ћk–CPѓоФрYЦ9®AЗЄбь ZюD
sАлГ«)ZЦўзSҐг	ШIAUҐ¦IЖпOЗљfЙG3bЛЏ¶гҐЙ·JWфmТшRgeИcя€UЄҐйјНґ—–-`,·•Љз}фммЌ’ЅЛWйЩц›DЁ§•нHµ&i7Џ):•ЗСS*!\ ,Сcj№_)‘f†!U7›_Ы†эo»Џ.m~»zlk`Ћ*нўыlnн¦&Оl®8™·gЫбТr?vІYБЖ§:vч>Ў°/?Ј$Ј§»{°шЄАrdђ"&i
з+^ВV^3цЖнСа!•Щр,і't};u}<MuOGХ|СR‚дiаMb{v8UБІЄЙг­[¬—с}ҐЃн;$TџµБ®b]ҐўЋ20jґxРиЬђ&8ПN·>щмГБЁт8—эҐр¦т2ж’8ѓ(Еaд<Апч©!ЮQGѓ<v’МћFУЩ4‰дб
жNcЫµ‚‰ч)`ЮЇЂоFС4Дnк%юЌ@oцµ?
wЄЙяRёГz|.Оfі™г'„<4Цп’х)ЃЮХEЈG8љНј8$огўј+YA<Љ€…vНьШпКVшN</uіФ<;єЉпцw‰{Ђ»НЪЗlѕљ]г8NПqc;}ЂЯ!нCьj*Џ€g1Й[Л#ѓьJ&џв0ј њ:ћя	`~%‘‡іАќ…й4vВЫЂ~п\~ЬяЩ\\;/ы¶ђ4›A’ypёЯ-нSВ]Ьt<ч'¶ѓ4МрЈВ]\;џ»м%й4фІЩЈguqнЂЎНBП#Уkp?{ыr¤¶Э—Х-ЭҐЯбЮюотЇ‰эNн6/	§37;{иHё[Ъ§Њ„ЛЪ4‘Д1±Э(sBыQ#бІl	$ћЪЎп^ЕЏ	—ҐлHрГ,АQ<#™w5фыЬ{„ЃwЯ0ё\°№R<aёЂРЁxМҐиTKm–„І”њWK>В‚З4'jm&.K3Б%ѕ\vЩСТwЙ`.P=$±тH-МWЌ):\в''Ж5C4,i:7Фµ’WТh\ґПylh*Wу”¬i2UcЊ[email protected]‚sҐхњс1ўЊJЉsЭIжОРSФE§џv;.iuw©©щЊІљ%’r6Ъ;//5џ5®PК“з№.{ №jФкqrцР\#УеАWПЃ†‘ЌzcяьґнЋючЗя+цt‘pO|ѕw– ®¶kD¶B&зЭ—)nљ„зП“Љ”а22juЈЭПќcс№ЫэaoФiЭP:Ь№б‡ћљSv‚*’џIт:Y™\m–IxQrAR	ъ;scњО­*’ЭЇц¦GXАРє&@3лЉ™”liEћK¦i„3хj:єОЏФЦqнSшяPъ¶м®ilЫУ™н'‘з{ЩPЌ}чю?Ж
»k‡о4ЕI'	Єq0;…я¦qГољЖ>г)СџЎ‡аЖрбPС°»Ћгi–О‚YжъішvЌ‹Н"pWфgЅџбuЈPдj`OџeШ±A9»ЈАО
,NМFЌ!bхNҐpЄµqb/QjПИy57>sхП8к+ШU’ZўFx“и5cлф!RПi†C?Ћќ,
<ХСµAугJ»СЇ‘«*Nў-9ќk ‹N8Ix­69_Rf-ъrI*†%ioюєдФLI†лцOлhзO±яr•ПIЮ'DЌбѕ¬ыё«СAєі^ЭЩ0о8лг®F‡p_У>оjtч¬‚s^џЂvВTц	 qyТлЫ“Ѓѕэ}e®Nъ

I
Ilya, 2016-10-23
@glebovgin

I have not so much a ready answer as some considerations:
1. Send a request directly to https://www.instagram.com/accounts/login / so that there are no 301 redirects. Yes, you have FOLLOWLOCATION, but that's me, just in case.
2. The meaning of this file_put_contents("insta_cookie.txt", $result_auth."\n", FILE_APPEND) is not clear at all.
Use
CURLOPT_COOKIEFILE, "insta_cookie.txt"
СURLOPT_COOKIEJAR, "insta_cookie.txt"
3. See $info = curl_getinfo($ ch1); - what there is from useful.
UPD. 4. And one more thing: curl_setopt($ch1, CURLOPT_ENCODING , "gzip");
In general, in the case of Instagram, I would use some kind of headless browser, such as CasperJS, because with php + curl you may have to suffer longer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question