【问题标题】:php, curl, headers and content-typephp、curl、标题和内容类型
【发布时间】:2010-11-10 06:17:14
【问题描述】:

我在处理服务器返回的 curl 和标头时遇到了一些问题。

1) 我在 my_website.com/index.php 上的 php 文件如下所示(精简版):

<?php

$url = 'http://my_content_server.com/index.php';

//Open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);

echo $result;
?>

my_content_server.com/index.php 上的 php 文件如下所示:

<?php
header("HTTP/1.0 404 Not Found - Archive Empty");
echo "Some content > 600 words to make chrome/IE happy......";
?>

我希望当我访问 my_website.com/index.php 时,我应该得到一个 404,但这并没有发生。

我做错了什么?

2) 基本上我想要实现的是:

my_content_server.com/index.php 将决定内容类型并发送适当的标头,而 my_website.com/index.php 应该只向浏览器发送相同的内容类型和其他标头(连同实际数据)。但似乎 my_website.com/index.php 正在编写自己的标题? (或者也许我不理解正确的工作方式)。

问候, JP

【问题讨论】:

  • header('HTTP/1.0 404 Not Found - Archive Empty'); exit;
  • 如果是最后一条语句,退出是否重要? (我想我可以在发送 404 标头后回显?)。
  • 我猜你想从my_content_server.com/index.php返回标题? ... ob_start(); $header = obj_get_contents()// your header; ob_end_clean(); header($header); echo "additional message"; 并使用@stillstanding 建议的curl_setopt($ch,CURLOPT_HEADER,true);
  • 是的,404之后可以回显任何东西。很多漂亮的404页面都是这样完成的。

标签: php curl http-headers


【解决方案1】:

curl_exec()之前插入:

curl_setopt($ch,CURLOPT_HEADER,true);

不仅仅是echo'ing 结果,还将标头转发给客户端:

list($headers,$content) = explode("\r\n\r\n",$result,2);
foreach (explode("\r\n",$headers) as $hdr)
    header($hdr);
echo $content;

【讨论】:

  • 这确实有影响,但是,不是我想要的。设置此标志后,标题由 my_website.com/index.php 逐字显示。 HTTP/1.0 404 Not Found - Archive Empty Date: Wed, 10 Nov 2010 08:09:30 GMT 服务器:Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.6 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g X-Powered-By:PHP/5.2.6-3ubuntu4.6 变化:Accept-Encoding Content-Length:282 Connection:close Content-Type:text/html。我客户端浏览还是没有收到404错误。
  • 感谢您的提示。这有一些我无法追踪的错误。我打开了 display_errors,得到了这个: 注意:未定义的偏移量:第 42 行 /var/www/index.php 中的 1 警告:标头可能不包含多个标头,检测到新行。在第 44 行的 /var/www/index.php 中。第 42 行是“爆炸”行,第 44 行是标题($hdr)。
  • 哇。知道了。 '\r\n\r\n' 和 '\r\n' 应该是 "\r\n\r\n" 和 "\r\n"。奇迹般有效。顺便说一句,重定向或“继续”标题或使用这种方法保持连接是否存在问题?
  • 如果 my_website.com/index.php 收到重定向(和其他标头),它也会将相同的标头转发给客户端。
  • 就内容服务器而言,cURL 客户端只是另一个 HTTP 客户端。并且连接不是直通的。您现在在 cURL 客户端有 2 个不同的 HTTP 连接 - 一个到内容服务器,另一个到最终用户。所以它充当代理。如果这不是您期望的行为,您可能需要过滤标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 2011-06-04
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多