ver tipos texto solucionar solucion servidor procesar petición métodos lista estados errors errores error elempleo ejecutar códigos código contpaqi como php header http-headers

tipos - Cómo enviar el error 500 Internal Server Error desde un script PHP



tipos de estados http (6)

PHP 5.4 tiene una función llamada http_response_code , por lo que si está utilizando PHP 5.4 puede hacer:

http_response_code(500);

He escrito un polyfill para esta función (Gist) si está ejecutando una versión de PHP en 5.4.

Para responder a su pregunta de seguimiento, el HTTP 1.1 RFC dice:

La razón de las frases enumeradas aquí son solo recomendaciones: PUEDEN ser reemplazadas por equivalentes locales sin afectar el protocolo.

Eso significa que puede usar el texto que desee (excluyendo los retornos de carro o las alimentaciones de línea) después del código en sí, y funcionará. En general, sin embargo, generalmente hay un mejor código de respuesta para usar. Por ejemplo, en lugar de usar un 500 para encontrar ningún registro, puede enviar un 404 (no encontrado), y para algo como "condiciones fallidas" (supongo que un error de validación), podría enviar algo como un 422 (no procesable) entidad).

Necesito enviar "500 Internal Server Error" desde un script PHP bajo ciertas condiciones. Se supone que el script debe ser llamado por una aplicación de terceros. La secuencia de comandos contiene un par de sentencias die("this happend") para las que necesito enviar el código de respuesta 500 Internal Server Error lugar del 200 OK normal. La secuencia de comandos de terceros volverá a enviar la solicitud bajo ciertas condiciones que incluyen no recibir el código de respuesta 200 OK .

Segunda parte de la pregunta: necesito configurar mi script de esta manera:

<?php custom_header( "500 Internal Server Error" ); if ( that_happened ) { die( "that happened" ) } if ( something_else_happened ) { die( "something else happened" ) } update_database( ); // the script can also fail on the above line // e.g. a mysql error occurred remove_header( "500" ); ?>

Necesito enviar el encabezado 200 solo después de que se haya ejecutado la última línea.

Editar

Una pregunta complementaria: ¿puedo enviar encabezados extraños 500 como estos?

HTTP/1.1 500 No Record Found HTTP/1.1 500 Script Generated Error (E_RECORD_NOT_FOUND) HTTP/1.1 500 Conditions Failed on Line 23

¿Serán dichos errores registrados por el servidor web?


Puede usar la siguiente función para enviar un cambio de estado:

function header_status($statusCode) { static $status_codes = null; if ($status_codes === null) { $status_codes = array ( 100 => ''Continue'', 101 => ''Switching Protocols'', 102 => ''Processing'', 200 => ''OK'', 201 => ''Created'', 202 => ''Accepted'', 203 => ''Non-Authoritative Information'', 204 => ''No Content'', 205 => ''Reset Content'', 206 => ''Partial Content'', 207 => ''Multi-Status'', 300 => ''Multiple Choices'', 301 => ''Moved Permanently'', 302 => ''Found'', 303 => ''See Other'', 304 => ''Not Modified'', 305 => ''Use Proxy'', 307 => ''Temporary Redirect'', 400 => ''Bad Request'', 401 => ''Unauthorized'', 402 => ''Payment Required'', 403 => ''Forbidden'', 404 => ''Not Found'', 405 => ''Method Not Allowed'', 406 => ''Not Acceptable'', 407 => ''Proxy Authentication Required'', 408 => ''Request Timeout'', 409 => ''Conflict'', 410 => ''Gone'', 411 => ''Length Required'', 412 => ''Precondition Failed'', 413 => ''Request Entity Too Large'', 414 => ''Request-URI Too Long'', 415 => ''Unsupported Media Type'', 416 => ''Requested Range Not Satisfiable'', 417 => ''Expectation Failed'', 422 => ''Unprocessable Entity'', 423 => ''Locked'', 424 => ''Failed Dependency'', 426 => ''Upgrade Required'', 500 => ''Internal Server Error'', 501 => ''Not Implemented'', 502 => ''Bad Gateway'', 503 => ''Service Unavailable'', 504 => ''Gateway Timeout'', 505 => ''HTTP Version Not Supported'', 506 => ''Variant Also Negotiates'', 507 => ''Insufficient Storage'', 509 => ''Bandwidth Limit Exceeded'', 510 => ''Not Extended'' ); } if ($status_codes[$statusCode] !== null) { $status_string = $statusCode . '' '' . $status_codes[$statusCode]; header($_SERVER[''SERVER_PROTOCOL''] . '' '' . $status_string, true, $statusCode); } }

Puedes usarlo como tal:

<?php header_status(500); if (that_happened) { die("that happened") } if (something_else_happened) { die("something else happened") } update_database(); header_status(200);


Puedes simplemente poner:

header("HTTP/1.0 500 Internal Server Error");

dentro de tus condiciones como:

if (that happened) { header("HTTP/1.0 500 Internal Server Error"); }

En cuanto a la consulta de la base de datos, puede hacer eso de esta manera:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

Debe recordar que debe colocar este código antes de cualquier etiqueta html (o salida).


Puedes simplificarlo así:

if ( that_happened || something_else_happened ) { header(''X-Error-Message: Incorrect username or password'', true, 500); die; }

Devolverá el siguiente encabezado:

HTTP/1.1 500 Internal Server Error ... X-Error-Message: Incorrect username or password ...

Agregado: Si necesita saber exactamente qué salió mal, haga algo como esto:

if ( that_happened ) { header(''X-Error-Message: Incorrect username'', true, 500); die(''Incorrect username''); } if ( something_else_happened ) { header(''X-Error-Message: Incorrect password'', true, 500); die(''Incorrect password''); }


Tu código debe verse así:

<?php if ( that_happened ) { header("HTTP/1.0 500 Internal Server Error"); die(); } if ( something_else_happened ) { header("HTTP/1.0 500 Internal Server Error"); die(); } // Your function should return FALSE if something goes wrong if ( !update_database() ) { header("HTTP/1.0 500 Internal Server Error"); die(); } // the script can also fail on the above line // e.g. a mysql error occurred header(''HTTP/1.1 200 OK''); ?>

Supongo que dejas de ejecutar si algo sale mal.


header($_SERVER[''SERVER_PROTOCOL''] . '' 500 Internal Server Error'', true, 500);