how to respond to a http request
Note that if you output data before sending the response then you will get a warning saying: Cannot modify header information - headers already sent. So do not echo any data in your responding script.
<?php
//process the request by fetching the info
$headers = http_get_request_headers();
$result = http_get_request_body();
//do stuff with the $headers and $result variables....
//then send your response
HttpResponse::status(200);
HttpResponse::setContentType('text/xml');
HttpResponse::setHeader('From', 'Lymber');
HttpResponse::setData('<?xml version="1.0"?><note>Thank you for posting your data! We love php!</note>');
HttpResponse::send();
?>
HttpResponse::send
(PECL pecl_http >= 0.10.0)
HttpResponse::send — Enviar respuesta
Descripción
static
bool HttpResponse::send
([ bool
$clean_ob = true
] )Envía finalmente la entidad.
Si se cachea con éxito, se finalizará la ejecución de PHP, y se escribirá una entrada en el registro siempre y cuando opción INI http.log.cache estuviera habilitado. Vea también la opción INI http.force_exit para ver a que sucede cuando "finaliza".
Parámetros
-
clean_ob -
indica si destruir o no tanto los manejadores de salidas que se hayan iniciado, como sus buffers
Valores devueltos
Devuelve TRUE en caso de éxito o FALSE en caso de error.
Ejemplos
Ejemplo #1 Ejemplo de HttpResponse::send()
<?php
HttpResponse::setCache(true);
HttpResponse::setContentType('application/pdf');
HttpResponse::setContentDisposition("$user.pdf", false);
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?>
lymber ¶
3 years ago
barnett dot [NOSPAM]thomas at gmail dot com ¶
5 years ago
I was having a problem with the bytes appended to the output, using the given example.
<?php
...
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?>
Content-Length mismatch: Response Header claimed x bytes, but server sent x+5 bytes.
Adding an exit statement solved this problem.
mbyrd at cloudcache dot net ¶
4 years ago
I figured out a way to return a response and then keep doing lots of other work:
<?php
HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');
HttpResponse::setData("<html>hellow world...</html>");
HttpResponse::send();
flush();
// Response has been sent
sleep(30);
define_syslog_variables();
openlog("cloudcacheLog", LOG_PID , LOG_LOCAL0);
syslog(LOG_INFO, "Writing log well after send and flush...");
?>
Response time according to LORI (firefox addon): 0.130s - tailing /var/log/syslog - message hits 30 seconds later.
