【发布时间】:2013-10-30 21:29:35
【问题描述】:
我想调用一个 URL 并希望通过使用 file_get_contents 使用 PHP 获取结果(我知道 CURL,但首先我想使用 file_get_contents 尝试它)。在我的情况下,它是对magento shop 系统的请求,它需要先前完成的后端登录。
如果我在浏览器中手动执行 URL,就会出现正确的页面。如果我使用file_get_contents 发送 URL,我也会登录(因为我在请求中添加了 Cookie),但每次我只获得仪表板主站点时,可能会导致重定向。
我尝试模拟相同的 http 请求,因为我的浏览器将其发送出去。我的问题是:是否可以直接将相同的标头数据(Cookie、Session-ID 等)作为参数发送到file_get_contents,而无需手动序列化?
这是一个常见的 PHP 问题,基本脚本是:
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
在我的例子中,代码是:
$postdata = http_build_query(
array
(
'selected_products' => 'some content',
)
);
$opts = array('http' =>
array
(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded; charset=UTF-8\r\n".
"Cookie: __utma=".Mage::getModel('core/cookie')->get("__utma").";".
"__utmz=".Mage::getModel('core/cookie')->get("__utmz").
" __utmc=".Mage::getModel('core/cookie')->get("__utmc").';'.
"adminhtml=".Mage::getModel('core/cookie')->get("adminhtml")."\r\n".
"X-Requested-With: XMLHttpRequest\r\n".
"Connection: keep-alive\r\n".
"Accept: text/javascript, text/html, application/xml, text/xml, */*\r\n".
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0",
'content' => $postdata
)
);
$context = stream_context_create($opts);
var_dump(file_get_contents($runStopAndRemoveProducts, false, $context ));
结果应该与我通过手动调用 URL 在浏览器中得到的错误消息相同(“请选择一些产品”作为纯文本),但响应是作为 html 网站的完整仪表板主页。
我正在寻找这样的脚本。我想确保所有参数都是自动设置的,无需手动构建 cookie 字符串和其他参数 :)
file_get_contents('http://example.com/submit.php', false, $_SESSION["Current_Header"]);
编辑:我发现了错误,需要两个特殊的 get-Parameter(isAjax=1 和 form_key = Mage::getSingleton('core/session', array('name' => 'adminhtml'))->getFormKey())。在我的情况下,form_key 会导致错误。但丑陋的 Cookie 字符串已经存在 - 仍在寻找更漂亮的解决方案。
【问题讨论】:
标签: php magento cookies http-headers file-get-contents