[英]Get access_token programmatically with php
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).
从浏览器登录后,我会得到一个access_token,它存储在cookie中(我想)。 How to get the access token programmatically using PHP (maybe using cURL) ?
如何使用PHP(也许使用cURL)以编程方式获取访问令牌?
I found a solution but it's written in python, how to do the same with PHP ? 我找到了一个解决方案,但是它是用python编写的,如何用PHP做到这一点?
Here is the solution with python 这是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
PHP can access cookies via the superglobal variable $_COOKIE
. PHP可以通过超全局变量
$_COOKIE
访问cookie。 To retrieve a specific cookie, echo $_COOKIE['name_of_cookie'];
要检索特定的cookie,请
echo $_COOKIE['name_of_cookie'];
. 。 To access all cookies, loop through them all
要访问所有cookie,请遍历所有cookie
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. 据我了解,一旦您收到此cookie(大概称为
access_token
),便希望使用此cookie卷曲页面。
This is a pretty good resource on how to fetch a URL with cookies. 这是有关如何使用Cookie提取URL的很好的资源。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.