2

I use php function file_get_contents and one of params is http headers. I make them such like this:

if (strpos($key, 'HTTP_') === 0) {
    $key = strtolower(strtr(substr($key, 5), '_', '-'));
    $this->headers .= $key . ': ' . $value . '\r\n';
}

but here is a problem, I should send headers in double quotes like this:

"Connection: close\r\nContent-Length: $data_len\r\n"

Here is an example of how do I make request:

$opts = array(
        'http'  =>  array(
            'method'    => "GET",
            'header'    => $this->headers
        )
);

$this->data = file_get_contents('http://phd.yandex.net/detect', false, stream_context_create($opts));

but it is fails. If I replace $this->headers in array with a custom string of http headers, everything works fine.

how to make it works right?

7
  • 1
    Have you considered cURL? Commented Oct 19, 2011 at 16:06
  • What's your custom string look like, v.s. what the above code generates? Commented Oct 19, 2011 at 16:06
  • 1
    Is it a typo that you omitted the quotes around \r\n? Commented Oct 19, 2011 at 16:07
  • You are missing quotes around the \r\n in the first code section - could this be the problem? I suspect it will not parse but you never know... Commented Oct 19, 2011 at 16:08
  • missing quotes around the \r\n it is a typo Commented Oct 19, 2011 at 16:09

1 Answer 1

5

The \r\n needs to be in double quotes so that the characters are parsed correctly. Everything else can be appended using single quotes, no problem. Only a few things are parsed using the backslash in single quoted strings, such as \\, \', and \".

Your headers are looking like this:

Key: Value\r\nKey: value\r\n

Where the \r\n is appearing as an actual string, when you want it to look like this:

Key: Value
Key: Value

Where the \r\n actually creates a new line in the headers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.