我有登录名和密码来连接到平台。从浏览器登录后,我将获得一个access_token,它存储在cookie中(我猜)。如何使用PHP以编程方式获取访问令牌(可能使用cURL)?
我找到了一个解决方案,但它是用python编写的,如何用PHP做同样的事情?
这是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
答案 0 :(得分:1)
PHP可以通过超全局变量$_COOKIE
访问cookie。要检索特定Cookie,echo $_COOKIE['name_of_cookie'];
。要访问所有cookie,请遍历所有cookie
foreach ($_COOKIE as $cookie) {
echo $cookie;
}
根据我的理解,一旦您收到此cookie(可能称为access_token
),您就想要使用此cookie来搜索一个页面。
This是如何使用Cookie获取网址的非常好的资源。从本质上讲,
$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);