postaddictme / instagram-php-scraper

Get account information, photos, videos, stories and comments.

Home Page:https://packagist.org/packages/raiym/instagram-php-scraper

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

loginWithSessionId throws an error

nelemur opened this issue · comments

loginWithSessionId throws InstagramAuthException: Login with session went wrong. Please report issue.
Response code is 302. Looks like Instagram made some changes. Session Id became longer.

Same here. Any fixes for this?

add the parameter ds_user_id = *id* to cookies headers generate
Don't forget to remove the check !isset in the Generate Header method related to ds_user_id

next, we are already working with new methods that Instagram has recently added

no one has ever helped me here, I hope I helped :)

public function loginWithSessionId($sessionId)
{
$split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE);
$our_id= $split[0][0];
$session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id];
.....

add the parameter ds_user_id = id to cookies headers generate Don't forget to remove the check !isset in the Generate Header method related to ds_user_id

next, we are already working with new methods that Instagram has recently added

no one has ever helped me here, I hope I helped :)

public function loginWithSessionId($sessionId) { $split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE); $our_id= $split[0][0]; $session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id]; .....

Not working

add the parameter ds_user_id = id to cookies headers generate Don't forget to remove the check !isset in the Generate Header method related to ds_user_id

next, we are already working with new methods that Instagram has recently added

no one has ever helped me here, I hope I helped :)

public function loginWithSessionId($sessionId) { $split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE); $our_id= $split[0][0]; $session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id]; .....

I did the same, this works.

add the parameter ds_user_id = id to cookies headers generate Don't forget to remove the check !isset in the Generate Header method related to ds_user_id
next, we are already working with new methods that Instagram has recently added
no one has ever helped me here, I hope I helped :)
public function loginWithSessionId($sessionId) { $split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE); $our_id= $split[0][0]; $session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id]; .....

Not working

As @ayd-is said dont forget to remove ds_user_id check in isLoggedIn function:

if (!isset($cookies['ds_user_id'])) {
return false;
}

It's not working for me. I changed the isLoggedIn function and added:
$split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE);
$our_id= $split[0][0];
$session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id];

to the loginWithSessionId function, but keeps the same "Login with session went wrong. Please report issue." response

It's not working for me. I changed the isLoggedIn function and added: $split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE); $our_id= $split[0][0]; $session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id];

to the loginWithSessionId function, but keeps the same "Login with session went wrong. Please report issue." response

It is necessary to correct this function and remove the check for ds_user_id:
!isset($cookies['ds_user_id'])

I changed two functions to :

public function loginWithSessionId($sessionId)
    {
        //$session = ['sessionid' => $sessionId, 'csrftoken' => md5( rand( 1, 5000 ) )];
        $split = preg_split('/%/', $sessionId, -1, PREG_SPLIT_OFFSET_CAPTURE);
        $our_id= $split[0][0];
        $session = ['sessionid' => $sessionId, 'csrftoken' => md5(rand(1, 5000)), 'ds_user_id' => $our_id];

        if (!$this->isLoggedIn($session)) {
            throw new InstagramAuthException('Login with session went wrong. Please report issue.');
        } else {
            $this->userSession = $session;
        }

        return $this->generateHeaders($this->userSession);
    }
public function isLoggedIn($session = null)
    {
        if ($session === null) {
            $session = static::$instanceCache->get($this->getCacheKey());
        }
        if (!isset($session['sessionid'])) {
            return false;
        }

        $sessionId = $session['sessionid'];
        $csrfToken = $session['csrftoken'];
        $ds_user_id = $session['ds_user_id'];
        $headers = [
            'cookie' => "ig_cb=1; csrftoken=$csrfToken; sessionid=$sessionId; ds_user_id=$ds_user_id;",
            'referer' => Endpoints::BASE_URL . '/',
            'x-csrftoken' => $csrfToken,
            'X-CSRFToken' => $csrfToken,
            'user-agent' => $this->getUserAgent(),
        ];
        $response = Request::get(Endpoints::BASE_URL, $headers);
        if ($response->code !== static::HTTP_OK) {
            return false;
        }
        $cookies = $this->parseCookies($response->headers);
        //if (!isset($cookies['ds_user_id'])) {
        //    return false;
        //}
        return true;
    }

still not working

note : I also didnt add ds_user_id to header and just removed isset.... part but it didnt work too

commented

still same here wkwk

Ok, here are my changes that work for me. Maybe this will help someone.

public function loginWithSessionId($sessionId)
  {
      $sessionParts = explode('%',$sessionId);
      $session = ['sessionid' => $sessionId, 'ds_user_id' => $sessionParts[0],'csrftoken' => md5( rand( 1, 5000 ) )];

      if (!$this->isLoggedIn($session)) {
          throw new InstagramAuthException('Login with session went wrong. Please report issue.');
      } else {
          $this->userSession = $session;
      }

      return $this->generateHeaders($this->userSession);
  }
public function isLoggedIn($session = null)
    {
        if ($session === null) {
            $session = static::$instanceCache->get($this->getCacheKey());
        }
        if (!isset($session['sessionid'])) {
            return false;
        }

        $sessionId = $session['sessionid'];
        $dsuserId = $session['ds_user_id'];
        $csrfToken = $session['csrftoken'];
        $headers = [
            'cookie' => "ig_cb=1; csrftoken=$csrfToken; sessionid=$sessionId; ds_user_id=$dsuserId",
            'referer' => Endpoints::BASE_URL . '/',
            'x-csrftoken' => $csrfToken,
            'X-CSRFToken' => $csrfToken,
            'user-agent' => $this->getUserAgent(),
        ];
        $response = Request::get(Endpoints::BASE_URL, $headers);
        if ($response->code !== static::HTTP_OK) {
            return false;
        }
        $cookies = $this->parseCookies($response->headers);
        /*
        if (!isset($cookies['ds_user_id'])) {
            return false;
        }
        */
        return true;
    }

There is one more important note, at this point. Seems like Instagram changed the user page structure and the function getAccount does not work anymore. I added this to be able to get the IG user id:

public function getAccountId($username)
  {
      $response = Request::get(Endpoints::getAccountPageLink($username), $this->generateHeaders($this->userSession));

      if (static::HTTP_NOT_FOUND === $response->code) {
          throw new InstagramNotFoundException('Account with given username does not exist.');
      }
      if (static::HTTP_OK !== $response->code) {
          throw new InstagramException('Response code is ' . $response->code . '. Body: ' . static::getErrorBody($response->body) . ' Something went wrong. Please report issue.', $response->code);
      }

      $userArray = self::extractSharedDataFromBodyNew($response->raw_body);
      if (!isset($userArray['require'][2][3][3]["rootView"]["props"]['id'])) {
          throw new InstagramException('Response code is ' . $response->code . '. Body: ' . static::getErrorBody($response->body) . ' Something went wrong. Please report issue.', $response->code);
      }
      return $userArray['require'][2][3][3]["rootView"]["props"]['id'];
  }

  private static function extractSharedDataFromBodyNew($body)
  {
      if (preg_match_all('~ScheduledApplyEach,(.*?)\);}\);}\);</script>~', $body, $out)) {
          return json_decode($out[1][0], true, 512, JSON_BIGINT_AS_STRING);
      }
      return null;
  }

I don't think this is the most elegant solution, but it works for now:

$instagram->loginWithSessionId('YOUR_SESSION_ID');
$userAccountId = $instagram->getAccountId('jlo');
$userMedias = $instagram->getMediasByUserId($userAccountId);
var_dump($userMedias);

Ok, here are my changes that work for me. Maybe this will help someone.

public function loginWithSessionId($sessionId)
  {
      $sessionParts = explode('%',$sessionId);
      $session = ['sessionid' => $sessionId, 'ds_user_id' => $sessionParts[0],'csrftoken' => md5( rand( 1, 5000 ) )];

      if (!$this->isLoggedIn($session)) {
          throw new InstagramAuthException('Login with session went wrong. Please report issue.');
      } else {
          $this->userSession = $session;
      }

      return $this->generateHeaders($this->userSession);
  }
public function isLoggedIn($session = null)
    {
        if ($session === null) {
            $session = static::$instanceCache->get($this->getCacheKey());
        }
        if (!isset($session['sessionid'])) {
            return false;
        }

        $sessionId = $session['sessionid'];
        $dsuserId = $session['ds_user_id'];
        $csrfToken = $session['csrftoken'];
        $headers = [
            'cookie' => "ig_cb=1; csrftoken=$csrfToken; sessionid=$sessionId; ds_user_id=$dsuserId",
            'referer' => Endpoints::BASE_URL . '/',
            'x-csrftoken' => $csrfToken,
            'X-CSRFToken' => $csrfToken,
            'user-agent' => $this->getUserAgent(),
        ];
        $response = Request::get(Endpoints::BASE_URL, $headers);
        if ($response->code !== static::HTTP_OK) {
            return false;
        }
        $cookies = $this->parseCookies($response->headers);
        /*
        if (!isset($cookies['ds_user_id'])) {
            return false;
        }
        */
        return true;
    }

There is one more important note, at this point. Seems like Instagram changed the user page structure and the function getAccount does not work anymore. I added this to be able to get the IG user id:

public function getAccountId($username)
  {
      $response = Request::get(Endpoints::getAccountPageLink($username), $this->generateHeaders($this->userSession));

      if (static::HTTP_NOT_FOUND === $response->code) {
          throw new InstagramNotFoundException('Account with given username does not exist.');
      }
      if (static::HTTP_OK !== $response->code) {
          throw new InstagramException('Response code is ' . $response->code . '. Body: ' . static::getErrorBody($response->body) . ' Something went wrong. Please report issue.', $response->code);
      }

      $userArray = self::extractSharedDataFromBodyNew($response->raw_body);
      if (!isset($userArray['require'][2][3][3]["rootView"]["props"]['id'])) {
          throw new InstagramException('Response code is ' . $response->code . '. Body: ' . static::getErrorBody($response->body) . ' Something went wrong. Please report issue.', $response->code);
      }
      return $userArray['require'][2][3][3]["rootView"]["props"]['id'];
  }

  private static function extractSharedDataFromBodyNew($body)
  {
      if (preg_match_all('~ScheduledApplyEach,(.*?)\);}\);}\);</script>~', $body, $out)) {
          return json_decode($out[1][0], true, 512, JSON_BIGINT_AS_STRING);
      }
      return null;
  }

I don't think this is the most elegant solution, but it works for now:

$instagram->loginWithSessionId('YOUR_SESSION_ID');
$userAccountId = $instagram->getAccountId('jlo');
$userMedias = $instagram->getMediasByUserId($userAccountId);
var_dump($userMedias);

is not work on me bro :( i just want to fetch the comments inside the post but i get an error

https://stackoverflow.com/questions/49265339/instagram-a-1-url-not-working-anymore-problems-with-graphql-query-to-get-da
https://www.instagram.com/graphql/query/?query_hash=33ba35852cb50da46f5b5e889df7d159&variables={"shortcode":"Bf-I2P6grhd","first":20,"after":"XXXXXXXX"}
https://www.instagram.com/someone/?__a=1 its not work

https://stackoverflow.com/questions/49265339/instagram-a-1-url-not-working-anymore-problems-with-graphql-query-to-get-da https://www.instagram.com/graphql/query/?query_hash=33ba35852cb50da46f5b5e889df7d159&variables={"shortcode":"Bf-I2P6grhd","first":20,"after":"XXXXXXXX"} https://www.instagram.com/someone/?__a=1 its not work

Request to this endpoint https://www.instagram.com/{username}/?__a=1 returns error.
Endpoint in your link may be the solution to get more account info (bio, followers count etc.). I found it too and testing now.
In my code above I was only able to get user ID and profile Picture.

As for getting comments I tried this with modified functions:

$instagram->loginWithSessionId('YOUR_SESSION_ID');
$userAccountId = $instagram->getAccountId('jlo');
$userMedias = $instagram->getMediasByUserId($userAccountId);
$comments = $instagram->getMediaCommentsById($userMedias[0]->getId(), 10);
var_dump($comments);

Hi! I also noticed that the request to the endpoint https://www.instagram.com/{username}/?__a=1 stopped working and after some searching I found that by adding the query parameter __d=dis solves the problem. So the new url woul be https://www.instagram.com/{username}/?__a=1&__d=dis.

This endpoint is used in the getAccountInfo method, not getAccount.

Hope this helps.

Hi! I also noticed that the request to the endpoint https://www.instagram.com/{username}/?__a=1 stopped working and after some searching I found that by adding the query parameter __d=dis solves the problem. So the new url woul be https://www.instagram.com/{username}/?__a=1&__d=dis.

This endpoint is used in the getAccountInfo method, not getAccount.

Hope this helps.

It helped a lot :) much easier to get user information in this way.

commented

I can confirm that my use-case is working again thanks to updated loginWithSessionId and isLoggedIn functions and &__d=dis appended to ACCOUNT_JSON_INFO. I will hopefully manage to send a PR.