Instagram登录程序 [英] Instagram login programatically

查看:1769
本文介绍了Instagram登录程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过我自己的网站以编程方式登录到Instagram,因为我想从Instagram检索直接消息(这需要一个登录,因为它不支持在Instagram的API(还))。但是Instagram的登录页面需要cookie才能登录。



我一直收到无法加载网页的消息,我可能需要启用Cookie。



有什么办法可以通过PHP以编程方式登录到Instagram吗?



这是我到目前为止。

  $ ch = curl_init('https://instagram.com/accounts/login/'); 
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ ch,CURLOPT_HEADER,1);
$ result = curl_exec($ ch);
preg_match_all('/ ^ Set-Cookie:\s *([^ \r\\\
] *)/ mi',$ result,$ ms);
$ cookies = array();
foreach($ ms [1] as $ m){
list($ name,$ value)= explode('=',$ m,2)
$ cookies [$ name] = $ value;
}

$ ccode = substr($ cookies ['ccode'],0,2);
$ mid = array_shift(explode(';',$ cookies ['mid'])));
$ csfrtoken = array_shift(explode(';',$ cookies ['csrftoken']));

$ header = array();
$ header [] ='Accept:* / *';
$ header [] ='Accept-Encoding:gzip,deflate';
$ header [] ='Accept-Language:nl-NL,nl; q = 0.8,en-US; q = 0.6,en; q = 0.4'
$ header [] ='Connection:keep-alive';
$ header [] ='Content-Length:46';
$ header [] ='Content-Type:application / x-www-form-urlencoded; charset = UTF-8';
$ header [] ='X-Instagram-AJAX:1';
$ header [] ='X-Requested-With:XMLHttpRequest';

$ ch = curl_init('https://instagram.com/accounts/login/ajax/');
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_POSTFIELDS,'username = *****& password = *****& intent =');
curl_setopt($ ch,CURLOPT_USERAGENT,'Mozilla / 5.0(Windows NT 6.3; WOW64)AppleWebKit / 537.36(KHTML,像Gecko)Chrome / 37.0.2062.120 Safari / 537.36'
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ header);
curl_setopt($ ch,CURLOPT_COOKIEJAR,dirname(__ FILE __)。'/ test.txt');
curl_setopt($ ch,CURLOPT_COOKIEFILE,dirname(__ FILE __)。'/ test.txt');
curl_setopt($ ch,CURLOPT_COOKIESESSION,true);
curl_setopt($ ch,CURLOPT_COOKIE,'mid ='。$ mid。'; ccode ='。$ ccode。'; csrftoken ='。$ csfrtoken。';');
curl_setopt($ ch,CURLOPT_ENCODING,'');

$ response = curl_exec($ ch);


解决方案

我非常尊重@FatihKısa的代码,非常好的工作。我试过这个代码,但现在它不工作,可能是因为一些Instagram服务器端的更改。我已经玩了2天他的代码,并强迫它与我的小变化。
这段代码的非常重要的部分是,Instagram只接受包含cookie数据(csrftoken和mid)的curl referrer的post形式。另一个重要的部分是您必须使用 https://www.instagram.com/accounts/login/ ?force_classic_login ,仅限于使用WWW并在Cookie创建关于curl info的字符串后删除:



#Netscape HTTP Cookie文件



#http://curl.haxx.se/docs/http-cookies.html



#此文件由libcurl生成!



b

  $ username =yourname; 
$ password =yourpass;
$ useragent =Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,像Gecko)Ubuntu Chromium / 50.0.2661.102 Chrome / 50.0.2661.102 Safari / 537.36;
$ cookie = $ username。。txt;

@unlink(dirname(__ FILE __)。/。$ cookie);

$ url =https://www.instagram.com/accounts/login/?force_classic_login;

$ ch = curl_init();

$ arrSetHeaders = array(
User-Agent:$ useragent,
'Accept:text / html,application / xhtml + xml,application / xml; q = 0.9 ,* / *; q = 0.8',
'Accept-Language:en-US,en; q = 0.5',
'Accept-Encoding:deflate,br',
'Connection :keep-alive',
'cache-control:max-age = 0',
);

curl_setopt($ ch,CURLOPT_HTTPHEADER,$ arrSetHeaders);
curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_COOKIEJAR,dirname(__ FILE __)。/。$ cookie);
curl_setopt($ ch,CURLOPT_COOKIEFILE,dirname(__ FILE __)。/。$ cookie);
curl_setopt($ ch,CURLOPT_USERAGENT,$ useragent);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ ch,CURLOPT_HEADER,1);
curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,1);

$ page = curl_exec($ ch);
curl_close($ ch);

//尝试找到实际的登录表单
if(!preg_match('/< form method =POSTid =login-formclass =adjacent ?< \ / form> / is',$ page,$ form)){
die('Failed to find log in form!
}

$ form = $ form [0];

//找到登录表单的动作
if(!preg_match('/ action =([^] +)/ i',$ form,$ action) {
die('无法找到登录表单url');
}

$ url2 = $ action [1]; //这是我们的新帖子url
//找到我们需要通过我们的登录发送的所有隐藏字段,包括安全令牌
$ count = preg_match_all('/< input type =hidden\s * name =([ ] *)\s * value =([^] *)/ i',$ form,$ hiddenFields);

$ postFields = array();

//将隐藏字段转换为数组
for($ i = 0; $ i <$ count; ++ $ i){
$ postFields [$ hiddenFields [1] [$ i]] = $ hiddenFields [2] [$ i];
}

//添加我们的登录值
$ postFields ['username'] = $ username;
$ postFields ['password'] = $ password;

$ post ='';

//转换为字符串,这不会作为数组, form不会接受multipart / form-data,只有application / x-www-form-urlencoded
foreach($ postFields as $ key => $ value){
$ post。 '='。 urlencode($ value)。 '&';
}

$ post = substr($ post,0,-1);

preg_match_all('/ ^ Set-Cookie:\s *([^;] *)/ mi',$ page,$ matches);

$ cookieFileContent ='';

foreach($ matches [1] as $ item)
{
$ cookieFileContent。=$ item;;
}

$ cookieFileContent = rtrim($ cookieFileContent,';');
$ cookieFileContent = str_replace('sessionid =;','',$ cookieFileContent);

$ oldContent = file_get_contents(dirname(__ FILE __)。/。$ cookie);
$ oldContArr = explode(\\\
,$ oldContent);

if(count($ oldContArr))
{
foreach($ oldContArr as $ k => $ line)
{
if ($ line,'#'))
{
unset($ oldContArr [$ k]);
}
}

$ newContent = implode(\\\
,$ oldContArr);
$ newContent = trim($ newContent,\\\
);

file_put_contents(
dirname(__ FILE __)。/。$ cookie,
$ newContent
);
}

$ arrSetHeaders = array(
'origin:https://www.instagram.com',
'authority:www.instagram.com',
'upgrade-insecure-requests:1',
'Host:www.instagram.com',
User-Agent:$ useragent,
'content-type: application / xhtml + xml,application / xml; q = 0.9,* / *; q = 0.8',
',应用程序/ x-www-form-urlencoded',
' Accept-Language:en-US,en; q = 0.5',
'Accept-Encoding:deflate,br',
Referer:$ url,
Cookie:$ cookieFileContent ,
'Connection:keep-alive',
'cache-control:max-age = 0',
);

$ ch = curl_init();
curl_setopt($ ch,CURLOPT_COOKIEJAR,dirname(__ FILE __)。/。$ cookie);
curl_setopt($ ch,CURLOPT_COOKIEFILE,dirname(__ FILE __)。/。$ cookie);
curl_setopt($ ch,CURLOPT_USERAGENT,$ useragent);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ ch,CURLOPT_HEADER,1);
curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ arrSetHeaders);
curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_REFERER,$ url);
curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_POSTFIELDS,$ post);

sleep(5);
$ page = curl_exec($ ch);


preg_match_all('/ ^ Set-Cookie:\s *([^;] *)/ mi',$ page,$ matches)
$ cookies = array();
foreach($ matches [1] as $ item){
parse_str($ item,$ cookie1);
$ cookies = array_merge($ cookie,$ cookie1);
}
var_dump($ page);

curl_Close($ ch);


I'm trying to programmatically login to Instagram via my own website because I want to retrieve direct messages from Instagram (this requires a login as it is not supported in the Instagram API (yet)). But the Instagram login page requires cookies to login.

I keep getting the message that the page could not be loaded and that I might need to enable cookies.

Is there any way possible to login programmatically via PHP to Instagram?

This is what I have so far.

$ch = curl_init('https://instagram.com/accounts/login/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^\r\n]*)/mi', $result, $ms);
$cookies = array();
foreach ($ms[1] as $m) {
   list($name, $value) = explode('=', $m, 2);
   $cookies[$name] = $value;
}

$ccode  = substr($cookies['ccode'], 0, 2);
$mid    = array_shift(explode(';', $cookies['mid']));
$csfrtoken = array_shift(explode(';', $cookies['csrftoken']));

$header = array();
$header[] = 'Accept: */*';
$header[] = 'Accept-Encoding: gzip,deflate';
$header[] = 'Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4';
$header[] = 'Connection: keep-alive';
$header[] = 'Content-Length: 46';
$header[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
$header[] = 'X-Instagram-AJAX: 1';
$header[] = 'X-Requested-With: XMLHttpRequest';

$ch = curl_init('https://instagram.com/accounts/login/ajax/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=*****&password=*****&intent=');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/test.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/test.txt');
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIE, 'mid='.$mid.'; ccode='.$ccode.'; csrftoken='.$csfrtoken.';');
curl_setopt($ch, CURLOPT_ENCODING, '');

$response = curl_exec($ch);

解决方案

My great respect to @Fatih Kısa for his code, very good job. I have tried this code, but for now it doesn't work, probably, because of some Instagram server-side changes. I have played 2 days with his code and force it to work with my small changes. Very important part of this code is that Instagram accepts only post form with curl referrer which contains the cookies data (csrftoken and mid). Also important part is that you must use https://www.instagram.com/accounts/login/?force_classic_login, only with WWW and to remove after cookies creation the strings about curl info:

#Netscape HTTP Cookie File

#http://curl.haxx.se/docs/http-cookies.html

#This file was generated by libcurl! Edit at your own risk.

Here is working code, enjoy!

$username = "yourname";
$password = "yourpass";
$useragent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36";
$cookie=$username.".txt";

@unlink(dirname(__FILE__)."/".$cookie);

$url="https://www.instagram.com/accounts/login/?force_classic_login";

$ch  = curl_init();        

$arrSetHeaders = array(
    "User-Agent: $useragent",
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language: en-US,en;q=0.5',
    'Accept-Encoding: deflate, br',
    'Connection: keep-alive',
    'cache-control: max-age=0',
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);         
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$page = curl_exec($ch);
curl_close($ch);          

// try to find the actual login form
if (!preg_match('/<form method="POST" id="login-form" class="adjacent".*?<\/form>/is', $page, $form)) {
    die('Failed to find log in form!');
}

$form = $form[0];

// find the action of the login form
if (!preg_match('/action="([^"]+)"/i', $form, $action)) {
    die('Failed to find login form url');
}

$url2 = $action[1]; // this is our new post url
// find all hidden fields which we need to send with our login, this includes security tokens
$count = preg_match_all('/<input type="hidden"\s*name="([^"]*)"\s*value="([^"]*)"/i', $form, $hiddenFields);

$postFields = array();

// turn the hidden fields into an array
for ($i = 0; $i < $count; ++$i) {
    $postFields[$hiddenFields[1][$i]] = $hiddenFields[2][$i];
}

// add our login values
$postFields['username'] = $username;
$postFields['password'] = $password;   

$post = '';

// convert to string, this won't work as an array, form will not accept multipart/form-data, only application/x-www-form-urlencoded
foreach($postFields as $key => $value) {
    $post .= $key . '=' . urlencode($value) . '&';
}

$post = substr($post, 0, -1);   

preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);

$cookieFileContent = '';

foreach($matches[1] as $item) 
{
    $cookieFileContent .= "$item; ";
}

$cookieFileContent = rtrim($cookieFileContent, '; ');
$cookieFileContent = str_replace('sessionid=; ', '', $cookieFileContent);

$oldContent = file_get_contents(dirname(__FILE__)."/".$cookie);
$oldContArr = explode("\n", $oldContent);

if(count($oldContArr))
{
    foreach($oldContArr as $k => $line)
    {
        if(strstr($line, '# '))
        {
            unset($oldContArr[$k]);
        }
    }

    $newContent = implode("\n", $oldContArr);
    $newContent = trim($newContent, "\n");

    file_put_contents(
        dirname(__FILE__)."/".$cookie,
        $newContent
    );    
}

$arrSetHeaders = array(
    'origin: https://www.instagram.com',
    'authority: www.instagram.com',
    'upgrade-insecure-requests: 1',
    'Host: www.instagram.com',
    "User-Agent: $useragent",
    'content-type: application/x-www-form-urlencoded',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language: en-US,en;q=0.5',
    'Accept-Encoding: deflate, br',
    "Referer: $url",
    "Cookie: $cookieFileContent",
    'Connection: keep-alive',
    'cache-control: max-age=0',
);

$ch  = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);     
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);        

sleep(5);
$page = curl_exec($ch);


preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie1);
    $cookies = array_merge($cookies, $cookie1);
}
var_dump($page);      

curl_close($ch);  

这篇关于Instagram登录程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆