Instagram Login Programmatically

Instagram login programmatically

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 data-encrypt 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);

How can I login to instagram using php and curl and get a sessionid?

change

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

for

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

Add

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

And you will be logged in.

It works:

define('USERNAME', "");
define('PASSWORD', "");
define('USERAGENT', "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
define('COOKIE', USERNAME.".txt");

function login_inst() {

@unlink(dirname(__FILE__)."/!instagram/".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__)."/!instagram/".COOKIE);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/!instagram/".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_SSL_VERIFYPEER, false);

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

//var_dump($page);

// 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__)."/!instagram/".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__)."/!instagram/".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__)."/!instagram/".COOKIE);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/!instagram/".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);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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);

}

This function return Instagram page by url:

function curl_inst($url) { 

$arrSetHeaders = array(
'origin: https://www.instagram.com',
'authority: www.instagram.com',
'method: GET',
'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:ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,uk;q=0.6',
'accept-encoding: deflate, br',
"Referer: https://www.instagram.com",
'Connection: keep-alive',
'cache-control: max-age=0',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/!instagram/".COOKIE);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/!instagram/".COOKIE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //connection timeout in seconds
curl_setopt($ch, CURLOPT_USERAGENT, USERAGENT);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$page = curl_exec($ch);

if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
//echo 'All OK: ', $http_code, "\n";
//var_dump($page);
curl_close($ch);
return $page;
default:
echo 'Error: ', $http_code, "\n";
curl_close($ch);
break;
}
}

}

Next step:

login_inst();
sleep(5);
$page = curl_inst('https://www.instagram.com/explore/tags/stackoverflow/');
var_dump($page);

Instagram how to get my user id from username?

Update in Jun-5-2022, Instagram API no longer use Bearer Token for authentication. But I find another useful API. All you need is added extra header X-IG-App-ID with "magic value".

https://i.instagram.com/api/v1/users/web_profile_info/?username=therock

Use can use my docker container Insta-Proxy-Server to bypass the authentication.

https://hub.docker.com/repository/docker/dockerer123456/insta-proxy-server

Demo video (I just run directly from source code): https://www.youtube.com/watch?v=frHC1jOfK1k


Update in Mar-19-2022, the API is require login now. Sorry for the bad news.

But we can solve this problem in two ways.

  1. Using my C# lib, login using your account (without any Instagram app token stuff and graph api.)
  2. In case the lib failed (I'm no longer maintain it long time ago), create a proxy server with logged in instagram account.

[Your app] --> [Proxy server] --> [Instagram] --> [Proxy server] -(forward)-> [Your app]

For Proxy server, you can use Nodejs app which install Chromium headless module (Puppeteer for example), logged in with an instagram account.

Proof of concept:

https://www.youtube.com/watch?v=ZlnNBpCXQM8

https://www.youtube.com/watch?v=eMb9us2hH3w


Update in June-20-2019, the API is public now. No authentication required.


Update in December-11-2018, I needed to confirm that this endpoint still work.

You need to login before sending request to this site because it's not public endpoint anymore.


Update in Apr-17-2018, it's look like this endpoint still working (but its not public endpoint anymore), you must send a request with extra information to that endpoint. (Press F12 to open developer toolbar, then click to Network Tab and trace the request.)


Update in Apr-12-2018, cameronjonesweb said that this endpoint doesn't work anymore. When he/she trying to access this endpoint, 403 status code return.


You can get user info when a request is made with the url below:

https://www.instagram.com/{username}/?__a=1

E.g:

This url will get all information about a user whose username is therock

https://www.instagram.com/therock/?__a=1

How can i login in instagram with python requests?

link = 'https://www.instagram.com/accounts/login/'
login_url = 'https://www.instagram.com/accounts/login/ajax/'

time = int(datetime.now().timestamp())
response = requests.get(link)
csrf = response.cookies['csrftoken']

payload = {
'username': username,
'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:{password}',
'queryParams': {},
'optIntoOneTap': 'false'
}

login_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"Referer": "https://www.instagram.com/accounts/login/",
"x-csrftoken": csrf
}

login_response = requests.post(login_url, data=payload, headers=login_header)
json_data = json.loads(login_response.text)

if json_data["authenticated"]:

print("login successful")
cookies = login_response.cookies
cookie_jar = cookies.get_dict()
csrf_token = cookie_jar['csrftoken']
print("csrf_token: ", csrf_token)
session_id = cookie_jar['sessionid']
print("session_id: ", session_id)
else:
print("login failed ", login_response.text)

You can find a complete guide here:

Share a post into your Instagram account using the requests library.

Instagram Login (Login with Facebook also) integration in android project

I find the solutions, may it help to others,

Please add following line in your InstagramDialog class

    WebSettings webSettings = mWebView.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);

Following line is important,

   webSettings.setDomStorageEnabled(true);

enable this option after that Instagram working fine.

I would imagine it is disabled by default for space savings and security.
Hope this help to many developers.
If you have same issue then accept this answeres.



Related Topics



Leave a reply



Submit