instagram-php-scraper icon indicating copy to clipboard operation
instagram-php-scraper copied to clipboard

loginWithSessionId throws an error

Open nelemur opened this issue 2 years ago • 16 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.

nelemur avatar Jun 29 '22 22:06 nelemur

Same here. Any fixes for this?

alina-ami avatar Jun 30 '22 09:06 alina-ami

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]; .....

ayd-is avatar Jun 30 '22 16:06 ayd-is

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

fonclub avatar Jun 30 '22 17:06 fonclub

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.

nelemur avatar Jun 30 '22 18:06 nelemur

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

nelemur avatar Jun 30 '22 18:06 nelemur

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

jesselafeber avatar Jun 30 '22 21:06 jesselafeber

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'])

ayd-is avatar Jul 01 '22 15:07 ayd-is

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

hossein1t avatar Jul 02 '22 06:07 hossein1t

still same here wkwk

nuzulr24 avatar Jul 05 '22 07:07 nuzulr24

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

nelemur avatar Jul 05 '22 08:07 nelemur

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

M4S3S7 avatar Jul 05 '22 16:07 M4S3S7

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

M4S3S7 avatar Jul 05 '22 16:07 M4S3S7

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

nelemur avatar Jul 06 '22 06:07 nelemur

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.

alina-ami avatar Jul 06 '22 07:07 alina-ami

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.

nelemur avatar Jul 06 '22 10:07 nelemur

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.

cuchac avatar Jul 07 '22 13:07 cuchac