J
J
JackShcherbakov2018-02-10 14:44:27
PHP
JackShcherbakov, 2018-02-10 14:44:27

Why is there no Content-Type header in the array returned by getAllHeaders()?

Hello! Wrote 2 scripts: the 1st sends requests, the 2nd answers them.
In the response that builds script number 2, I want to make sure the Content-Type header of the response is set correctly by writing code like this:

//Упрощенная версия скрипта номер 2

       eader("Content-Type:text/html"); // Не выведится в цикле ниже
  foreach (getallheaders() as $name => $value) {
    	       echo "<br> $name: $value";
  }

Here are 2 scripts in their entirety:
1st:
<?php
  $c = curl_init("http://asd/newFolder/formhandler.php");
  curl_setopt($c, CURLOPT_HTTPHEADER, array("Accept:application/json"));
  curl_exec($c);

?>

2nd:
<?php
  $formats = array("application/json", "text/html");
  $default_format = "application/json";

  if($_SERVER["HTTP_ACCEPT"]){
    if(in_array($_SERVER["HTTP_ACCEPT"], $formats)){
      $format = $_SERVER["HTTP_ACCEPT"];
    }else{
      print "Клиент просит неподдерживаемый формат!";
      exit();
    }
  }
  else{
    $format = $default_format;
  }

  header("Content-Type:$format");
  //Строим тело ответа
  if($format == "application/json"){
      print "Клиенту нужен json";
  }
  else if($format == "text/html"){
print <<<HTML
          <!DOCTYPE html>
          <html>
            <head>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
              <title>Манипулирование файлами</title>
            </head>
          <body>
            <p>Клиенту нужен HTML</p>
          </body>
          </html>	
HTML;
  }
                                                          //ТУТ НЕПОНЯТНО!
  foreach (getallheaders() as $name => $value) {
    	echo "<br> $name: $value";
  }

?>

Result of executing script 1:
Клиенту нужен json
Host: asd
Accept: application/json

Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2018-02-10
@JackShcherbakov

The "header" function adds a header that will be sent to the client.
The "getallheaders" function returns all the headers that were received from the client .
That is, in your case, getallheaders will return what is set in the first script:
To get headers ready to be sent, use the headers_list function .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question