php, curl, headers and content-type

耗尽温柔 提交于 2019-12-07 22:48:07

问题


I am having some trouble working with curl and headers returned by servers.

1) My php file on my_website.com/index.php looks like this (trimmed version):

<?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;
?>

The php file on my_content_server.com/index.php looks like this:

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

I expect that when I visit my_website.com/index.php, I should get a 404, but that is not happening.

What am I doing wrong?

2) Basically what I want to achieve is:

my_content_server.com/index.php will decide the content type and send appropriate headers, and my_website.com/index.php should just send the same content-type and other headers (along with actual data) to the browser. But it seems that my_website.com/index.php is writing its own headers? (Or maybe I am not understanding the working correctly).

regards, JP


回答1:


Insert before curl_exec():

curl_setopt($ch,CURLOPT_HEADER,true);

Instead of just echo'ing the result, forward the headers to the client as well:

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


来源:https://stackoverflow.com/questions/4141750/php-curl-headers-and-content-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!