首页 > 解决方案 > 保持在读取的文件上生成的 cookie 仍然存在于下一个读取的其他文件中 php

问题描述

所以我想用 PHP 从https://www.mangaeden.com/api/mymanga(我称之为“第一个文件”)进行 API 调用,以 JSON 格式检索我的个人数据(例如我最喜欢的漫画等) ,但要做到这一点,我必须从https://www.mangaeden.com/ajax/login/?username=xxx&password=xxx登录(我称之为“第二个文件”),该文件包含一个用于存储 cookie 的程序,其中包含我从 URL 参数中提供的用户名和密码。

当我使用 cURL 函数运行第一个文件以发送标头时,包含我的用户名和密码在内的 cookie 数据的标头已成功发送,但之后当我调用第二个文件发送我的个人数据时,cookie 不存在所以我的数据文件没有出现。

function run_set_cookie_function_inside_this_file($file_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $file_url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_exec($ch);
    curl_close($ch);
}

// if this file is executed, the user's username and password will be stored in cookies
run_set_cookie_function_inside_this_file("https://www.mangaeden.com/ajax/login/?username=xxx&password=xxx");
// this file requires user's username and password which stored in cookies to return other data (example: user's favorite movie, pet, etc.)
echo file_get_contents("https://www.mangaeden.com/api/mymanga/");

注意:这2个文件(第一个和第二个文件)不是我的,所以我不能更改里面的程序代码

那是我的问题,所以我的问题是如何保持在第一个文件中制作的 cookie 仍然存在于第二个文件中?

对不起,我的英语不好和难以理解的凌乱句子。十分感谢你的帮助!

标签: phprestcurlphp-curl

解决方案


                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,'https://www.mangaeden.com/ajax/login/?username=xxx&password=xxx');
                curl_setopt($ch, CURLOPT_COOKIE, true);
                curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                curl_exec($ch);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,'https://www.mangaeden.com/api/mymanga/');
                curl_setopt($ch, CURLOPT_COOKIE, true);
                curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                $output = curl_exec($ch);
                echo $output;
                curl_close($ch)

我有这样的登录,第一个 curl 和第二个请求 api!


推荐阅读