我想获取我的 Gmail 帐户中一些电子邮件的内容。我想使用 PHP cURL 扩展来执行此操作。我在第一次尝试中遵循了以下步骤:
- 在PHP代码中,输出https://www.google.com/accounts/ServiceLoginAuth的内容.
- 用户在浏览器中输入用户名和密码进行登录。
- 在 PHP 代码中,将 Cookie 保存在名为 cookie.txt 的文件中。
- 在 PHP 代码中,将请求发送至 https://mail.google.com/以及从 cookie.txt 检索的 cookie 并输出内容。
以下代码不起作用:
$login_url = 'https://www.google.com/accounts/ServiceLoginAuth';
$gmail_url = 'https://mail.google.com/';
$cookie_file = dirname(__FILE__) . '/cookie.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_URL, $login_url);
$output = curl_exec($ch);
echo $output;
curl_setopt($ch, CURLOPT_URL, $gmail_url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
最佳答案
你的做法是错误的。您无法检索 https://www.google.com/accounts/ServiceLoginAuth 的内容并输出它,期望用户填写详细信息并按登录。由于表单定义为
<form action="https://www.google.com/accounts/ServiceLoginAuth" method="post">
登录详细信息将由浏览器提交到该页面,并且您的脚本永远不会获取 cookie。您需要向https://www.google.com/accounts/ServiceLoginAuth提交post请求已有用户名和密码。只有这样,curl 才会收到带有 cookie 的响应。
也就是说,我建议您清除所有这些内容,在 GMail 中启用 IMAP 并使用它来访问您的电子邮件。
关于php - 使用 PHP cURL 扩展在两个网站之间共享相同的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2845684/