Reputation: 5587
I have a login and password to connect to a platform. After login from browser I will get an access_token it's stored in cookie (I guess). How to get the access token programmatically using PHP (maybe using cURL) ?
I found a solution but it's written in python, how to do the same with PHP ?
Here is the solution with python
import urllib
import urllib2
import cookielib
import json
import logging
class GISTokenGenerator:
def __init__(self, email, password):
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
self.email = email
self.login_data = urllib.urlencode({'user[email]': email, 'user[password]': password})
def generate_token(self):
logging.info('Generating a token for {0}...'.format(self.email))
self.opener.open('https://site/users/sign_in', self.login_data)
for cookie in self.cj:
if cookie.name == 'aiesec_token':
token_json = json.loads(urllib.unquote(cookie.value))
token = token_json['token']['access_token']
if token is None:
raise Exception('Unable to generate a token for {0}!'.format(self.email))
return token
Upvotes: 0
Views: 646
Reputation: 2163
PHP can access cookies via the superglobal variable $_COOKIE
. To retrieve a specific cookie, echo $_COOKIE['name_of_cookie'];
. To access all cookies, loop through them all
foreach ($_COOKIE as $cookie) {
echo $cookie;
}
As I understand it, once your receive this cookie (presumable called access_token
), you want to cURL a page with this cookie.
This is a pretty good resource on how to fetch a URL with cookies. Essentially,
$c = curl_init('http://www.example.com/needs-cookies.php');
curl_setopt($c, CURLOPT_VERBOSE, 1);
curl_setopt($c, CURLOPT_COOKIE, 'access_token=' . $_COOKIE['access_token']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($c);
curl_close($c);
Upvotes: 1