file_get_contents api链接两个与会话的连接

时间:2016-02-19 19:26:25

标签: php api session file-get-contents

我有两个api页面,api1.php和api2.php。在1上设置会话,在2上需要返回此会话。 当然会有其他功能,但我的目标是通过使用会话将这两个api连接链接到一个和另一个。

api1.php:

session_start();

$api_key = 'dfdsakdsfjdskfjdskfdsjfdfewfifjjsd';

$_SESSION['api_key'] = $api_key;
setcookie('api_key', $api_key);

api2.php:

session_start();

echo $_SESSION['api_key'];
echo $_COOKIE['api_key'];

test.php的:

$url = 'http://example.com/api1.php';
$content1 = file_get_contents($url);

$url2 = 'http://example.com/api2.php'; 
$content2 = file_get_contents($url2);
echo $content2;

您可能已经注意到,我正在访问test.php页面以获取结果。 但没有结果返回。 有人可以告诉我为什么这不起作用,还有什么可能是让这一切成为现实的另一种方式?

(注意:example.com都是同一个网站(我的))

1 个答案:

答案 0 :(得分:1)

您的代码"链接"正确。问题实际上在test.php中!它不是执行两个文件中包含的代码,而是检索整个文件。如果您查看源代码,您将记下PHP标记和代码。检查这是否有效的更好解决方案是分别转到api1.php和api2.php。通过一些代码调整,您还可以使用include()或require()函数。看起来像这样:

api2.php

echo $_SESSION['api_key'] . "\n<br/>\n";
echo $_COOKIE['api_key'];

test.php的

include('api1.php');
include('api2.php');

值得注意的是,使用include和require函数执行api1.php和api2.php中的代码,就像该代码是test.php的一部分一样。