send custom HTTP response with PHP

℡╲_俬逩灬. 提交于 2020-01-17 08:47:17

问题


I want to send a custom HTTP response back to an application requesting a GET to a php script. The body is will be in binary format (octet-streams). I'm wondering if there is a simple way to do this? I am looking into the HttpResponse class in PECL but is having trouble installing it right now. I do not really need all the other functionalities that goes with it so I'm looking for something simpler.

Any help would be appreciated.


回答1:


PHP has a header() function built in, so you can customise your response without requiring extra libraries:

<?php

header('Content-Type: application/octet-stream');
header('X-Powered-By: l3utterfly');

echo $binary_data;

?>



回答2:


You can always set HTTP Headers using header() function, and then simply output binary data using print, echo or any other usual way. Send Content-Type http header to octet stream and it should work all right.




回答3:


You can use the header function to send back whatever response you want. If you want to send back custome response codes, you could use:

<?
  $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');

  //change the code and message to whatever. But I would keep it valid codes so browsers can handle it.
  //see http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

  header($protocol . ' 404 Not Found');
  exit();
?>

And if you want to send binary data, change the header to the correct content-type and echo the binary data.



来源:https://stackoverflow.com/questions/17146647/send-custom-http-response-with-php

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