Php get http error message



error_get_last

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

error_get_last — Get the last occurred error

Description

Gets information about the last error that occurred.

Parameters

This function has no parameters.

Return Values

Returns an associative array describing the last error with keys «type», «message», «file» and «line». If the error has been caused by a PHP internal function then the «message» begins with its name. Returns null if there hasn’t been an error yet.

Examples

Example #1 An error_get_last() example

The above example will output something similar to:

See Also

User Contributed Notes 13 notes

[Editor’s note: as of PHP 7.0.0 there is error_clear_last() to clear the most recent error.]

To clear error_get_last(), or put it in a well defined state, you should use the code below. It works even when a custom error handler has been set.

// var_dump or anything else, as this will never be called because of the 0
set_error_handler ( ‘var_dump’ , 0 );
@ $undef_var ;
restore_error_handler ();

// error_get_last() is now in a well known state:
// Undefined variable: undef_var

Function error_get_last() will return an error information even if the error is hidden because you’ve used character @, because of the «error_reporting» directive in the php.ini file, or because you’ve used function error_reporting().

( E_ALL ^ E_NOTICE );
$y = $x ;
$err = error_get_last ();
var_export ( $err );
?>
Will display: array ( ‘type’ => 8, ‘message’ => ‘Undefined variable: x’, ‘file’ => ‘test.php’, ‘line’ => 4, )

= @ $x ;
$err = error_get_last ();
var_export ( $err );
?>
Will display: array ( ‘type’ => 8, ‘message’ => ‘Undefined variable: x’, ‘file’ => ‘test.php’, ‘line’ => 4, )

The error_get_last() function will give you the most recent error even when that error is a Fatal error.

function handleFatalPhpError () <
$last_error = error_get_last ();
if( $last_error [ ‘type’ ] === E_ERROR ) <
echo «Can do custom output and/or logging for fatal error here. » ;
>
>

To know if something happened between two statements one can of course use a special string with user_error() (in lieu of a built-in special reset mentioned by mail at mbaierl dot com): @ user_error ( $error_get_last_mark = ‘error_get_last mark’ );
$not_set ;
$error_get_last = error_get_last ();
$something_happened =( $error_get_last [ ‘message’ ]!= $error_get_last_mark ); ?>

If your (function) ?> function returns true then you’ll have to roll you own error_get_last functionality. (Shortly mentioned by dmgx dot michael at gmail dot com).

To manual moderators: Re php.net/manual/add-note.php: Since i guess the above technically sorts under «References to other notes» i feel the need to defend myself with that i’m thinking it might show for usability where other’s say it fails and no, i haven’t got any other medium to reach the readers of the php manual notes.
Also, you could have some examples of what notes you think is okay. Thanks for your moderation.

Like $php_errormsg, the return value of this function may not be updated if a user-defined error handler returns non-FALSE. Tested on PHP 5.2.6.

( PHP_VERSION );
// Outputs: string(5) «5.2.6»

@ trigger_error ( «foo» );
$e = error_get_last ();
var_dump ( $e [ ‘message’ ]);
// Outputs: string(3) «foo»

set_error_handler ( create_function ( ‘$a,$b’ , » ));

@ trigger_error ( «bar» );
$e = error_get_last ();
var_dump ( $e [ ‘message’ ]);
// Outputs: string(3) «foo»

set_error_handler ( create_function ( ‘$a,$b’ , ‘return false;’ ));

@ trigger_error ( «baz» );
$e = error_get_last ();
var_dump ( $e [ ‘message’ ]);
// Outputs: string(3) «baz»
?>

Beware that registing a shutdown function to catch errors won’t work if other shutdown functions throw errors.

( ‘cleanupObjects’ );
register_shutdown_function ( ‘handleFatalPhpError’ );

function cleanupObjects () <
trigger_error ( ‘An insignificant problem’ , E_USER_WARNING );
>

function handleFatalPhpError () <
$last_error = error_get_last ();
if( $last_error [ ‘type’ ] === E_ERROR || $last_error [ ‘type’ ] === E_USER_ERROR ) <
echo «Can do custom output and/or logging for fatal error here. » ;
>
>

trigger_error ( ‘Something serious’ , E_USER_ERROR );

?>

In the above code, $last_error will contain the warning, becuase cleanupObjects() is called first.

This is a simple debugging script for mail functions.

//Built By Manomite for Debugging

error_reporting ( E_ALL ^ E_NOTICE );
$err = error_get_last ();

$res = «An error has occurred in your application sir.\n Details Include » . $err . «»

mail ( «admin@manomite.net» , «Error Occurred» , $res , $from );
>
>
>
?>

If you have the need to check whether an error was a fatal error before PHP 5.2 (in my case, within an output buffer handler), you can use the following hack:

# Check if there was a PHP fatal error.
# Using error_get_last is the «right» way, but it requires PHP 5.2+. The back-up is a hack.
if ( function_exists ( ‘error_get_last’ )) <
$lastPHPError = error_get_last ();
$phpFatalError = isset( $lastPHPError ) && $lastPHPError [ ‘type’ ] === E_ERROR ;
> else <
$phpFatalError = strstr ( $output , ‘Fatal error:’ ) && ! strstr ( $output , ‘ ‘ );
>
?>

Читайте также:  Error incorrect username and or password

This is, of course, language-dependent, so it wouldn’t be good in widely-distributed code, but it may help in certain cases (or at least be the base of something that would work).

While mail at mbaierl dot com makes the point that this function isn’t best for reporting the possible error condition of the most recently executed step, there are situations in which it is especially helpful to know the last error—regardless of when it occurred.

As an example, imagine if you had some code that captured the output from dynamic pages, and cached it for faster delivery to subsequent visitors. A final sanity check would be to see if an error has occurred anywhere during the execution of the script. If there has been an error, we probably don’t want to cache that page.

Источник

http_response_code

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

http_response_code — Получает или устанавливает код ответа HTTP

Описание

Получает или задаёт коды ответов HTTP.

Список параметров

Код ответа устанавливается с помощью опционального параметра response_code .

Возвращаемые значения

Если response_code задан, то будет возвращён предыдущий код статуса. Если response_code не задан, то будет возвращён текущий код статуса. Оба этих значения будут по умолчанию иметь код состояния 200 , если они используются в окружении веб-сервера.

Если response_code не задан и используется не в окружении веб-сервера (например, в CLI), то будет возвращено false . Если response_code задан и используется не в окружении веб-сервера, то будет возвращено true (но только если не был установлен предыдущий код статуса).

Примеры

Пример #1 Использование http_response_code() в окружении веб-сервера

// Берём текущий код и устанавливаем новый
var_dump ( http_response_code ( 404 ));

// Берём новый код
var_dump ( http_response_code ());
?>

Результат выполнения данного примера:

Пример #2 Использование http_response_code() в CLI

// Берём текущий код по умолчанию
var_dump ( http_response_code ());

// Устанавливаем код
var_dump ( http_response_code ( 201 ));

// Берём новый код
var_dump ( http_response_code ());
?>

Результат выполнения данного примера:

Смотрите также

  • header() — Отправка HTTP-заголовка
  • headers_list() — Возвращает список переданных заголовков (или готовых к отправке)

User Contributed Notes 18 notes

If your version of PHP does not include this function:

if (! function_exists ( ‘http_response_code’ )) <
function http_response_code ( $code = NULL ) <

switch ( $code ) <
case 100 : $text = ‘Continue’ ; break;
case 101 : $text = ‘Switching Protocols’ ; break;
case 200 : $text = ‘OK’ ; break;
case 201 : $text = ‘Created’ ; break;
case 202 : $text = ‘Accepted’ ; break;
case 203 : $text = ‘Non-Authoritative Information’ ; break;
case 204 : $text = ‘No Content’ ; break;
case 205 : $text = ‘Reset Content’ ; break;
case 206 : $text = ‘Partial Content’ ; break;
case 300 : $text = ‘Multiple Choices’ ; break;
case 301 : $text = ‘Moved Permanently’ ; break;
case 302 : $text = ‘Moved Temporarily’ ; break;
case 303 : $text = ‘See Other’ ; break;
case 304 : $text = ‘Not Modified’ ; break;
case 305 : $text = ‘Use Proxy’ ; break;
case 400 : $text = ‘Bad Request’ ; break;
case 401 : $text = ‘Unauthorized’ ; break;
case 402 : $text = ‘Payment Required’ ; break;
case 403 : $text = ‘Forbidden’ ; break;
case 404 : $text = ‘Not Found’ ; break;
case 405 : $text = ‘Method Not Allowed’ ; break;
case 406 : $text = ‘Not Acceptable’ ; break;
case 407 : $text = ‘Proxy Authentication Required’ ; break;
case 408 : $text = ‘Request Time-out’ ; break;
case 409 : $text = ‘Conflict’ ; break;
case 410 : $text = ‘Gone’ ; break;
case 411 : $text = ‘Length Required’ ; break;
case 412 : $text = ‘Precondition Failed’ ; break;
case 413 : $text = ‘Request Entity Too Large’ ; break;
case 414 : $text = ‘Request-URI Too Large’ ; break;
case 415 : $text = ‘Unsupported Media Type’ ; break;
case 500 : $text = ‘Internal Server Error’ ; break;
case 501 : $text = ‘Not Implemented’ ; break;
case 502 : $text = ‘Bad Gateway’ ; break;
case 503 : $text = ‘Service Unavailable’ ; break;
case 504 : $text = ‘Gateway Time-out’ ; break;
case 505 : $text = ‘HTTP Version not supported’ ; break;
default:
exit( ‘Unknown http status code «‘ . htmlentities ( $code ) . ‘»‘ );
break;
>

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

header ( $protocol . ‘ ‘ . $code . ‘ ‘ . $text );

$GLOBALS [ ‘http_response_code’ ] = $code ;

$code = (isset( $GLOBALS [ ‘http_response_code’ ]) ? $GLOBALS [ ‘http_response_code’ ] : 200 );

?>

In this example I am using $GLOBALS, but you can use whatever storage mechanism you like. I don’t think there is a way to return the current status code:

For reference the error codes I got from PHP’s source code:

And how the current http header is sent, with the variables it uses:

Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).

The following codes currently work as expected (with PHP running as Apache module):
200 – 208, 226
300 – 305, 307, 308
400 – 417, 422 – 424, 426, 428 – 429, 431
500 – 508, 510 – 511

Читайте также:  Steam wallet code error

Codes 0, 100, 101, and 102 will be sent as «200 OK».

Everything else will result in «500 Internal Server Error».

If you want to send responses with a freestyle status line, you need to use the `header()` function:

( «HTTP/1.0 418 I’m A Teapot» ); ?>

When setting the response code to non-standard ones like 420, Apache outputs 500 Internal Server Error.

This happens when using header(0,0,420) and http_response_code(420).
Use header(‘HTTP/1.1 420 Enhance Your Calm’) instead.

Note that the response code in the string IS interpreted and used in the access log and output via http_response_code().

Status codes as an array:

= 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» , 306 => «(Unused)» , 307 => «Temporary Redirect» , 308 => «Permanent 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» , 418 => «I’m a teapot» , 419 => «Authentication Timeout» , 420 => «Enhance Your Calm» , 422 => «Unprocessable Entity» , 423 => «Locked» , 424 => «Failed Dependency» , 424 => «Method Failure» , 425 => «Unordered Collection» , 426 => «Upgrade Required» , 428 => «Precondition Required» , 429 => «Too Many Requests» , 431 => «Request Header Fields Too Large» , 444 => «No Response» , 449 => «Retry With» , 450 => «Blocked by Windows Parental Controls» , 451 => «Unavailable For Legal Reasons» , 494 => «Request Header Too Large» , 495 => «Cert Error» , 496 => «No Cert» , 497 => «HTTP to HTTPS» , 499 => «Client Closed Request» , 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» , 508 => «Loop Detected» , 509 => «Bandwidth Limit Exceeded» , 510 => «Not Extended» , 511 => «Network Authentication Required» , 598 => «Network read timeout error» , 599 => «Network connect timeout error» );
?>

Source: Wikipedia «List_of_HTTP_status_codes»

Do not mix the use of http_response_code() and manually setting the response code header because the actual HTTP status code being returned by the web server may not end up as expected. http_response_code() does not work if the response code has previously been set using the header() function. Example:

( ‘HTTP/1.1 401 Unauthorized’ );
http_response_code ( 403 );
print( http_response_code ());
?>

The raw HTTP response will be (notice the actual status code on the first line does not match the printed http_response_code in the body):

HTTP/1.1 401 Unauthorized
Date: Tue, 24 Nov 2020 13:49:08 GMT
Server: Apache
Connection: Upgrade, Keep-Alive
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

I only tested it on Apache. I am not sure if this behavior is specific to Apache or common to all PHP distributions.

You can also create a enum by extending the SplEnum class.
/** HTTP status codes */
class HttpStatusCode extends SplEnum <
const __default = self :: OK ;

const SWITCHING_PROTOCOLS = 101 ;
const OK = 200 ;
const CREATED = 201 ;
const ACCEPTED = 202 ;
const NONAUTHORITATIVE_INFORMATION = 203 ;
const NO_CONTENT = 204 ;
const RESET_CONTENT = 205 ;
const PARTIAL_CONTENT = 206 ;
const MULTIPLE_CHOICES = 300 ;
const MOVED_PERMANENTLY = 301 ;
const MOVED_TEMPORARILY = 302 ;
const SEE_OTHER = 303 ;
const NOT_MODIFIED = 304 ;
const USE_PROXY = 305 ;
const BAD_REQUEST = 400 ;
const UNAUTHORIZED = 401 ;
const PAYMENT_REQUIRED = 402 ;
const FORBIDDEN = 403 ;
const NOT_FOUND = 404 ;
const METHOD_NOT_ALLOWED = 405 ;
const NOT_ACCEPTABLE = 406 ;
const PROXY_AUTHENTICATION_REQUIRED = 407 ;
const REQUEST_TIMEOUT = 408 ;
const CONFLICT = 408 ;
const GONE = 410 ;
const LENGTH_REQUIRED = 411 ;
const PRECONDITION_FAILED = 412 ;
const REQUEST_ENTITY_TOO_LARGE = 413 ;
const REQUESTURI_TOO_LARGE = 414 ;
const UNSUPPORTED_MEDIA_TYPE = 415 ;
const REQUESTED_RANGE_NOT_SATISFIABLE = 416 ;
const EXPECTATION_FAILED = 417 ;
const IM_A_TEAPOT = 418 ;
const INTERNAL_SERVER_ERROR = 500 ;
const NOT_IMPLEMENTED = 501 ;
const BAD_GATEWAY = 502 ;
const SERVICE_UNAVAILABLE = 503 ;
const GATEWAY_TIMEOUT = 504 ;
const HTTP_VERSION_NOT_SUPPORTED = 505 ;
>

if you need a response code not supported by http_response_code(), such as WebDAV / RFC4918’s «HTTP 507 Insufficient Storage», try:

( $_SERVER [ ‘SERVER_PROTOCOL’ ] . ‘ 507 Insufficient Storage’ );
?>
result: something like

Читайте также:  Utorrent http error 451

HTTP/1.1 507 Insufficient Storage

The note above from «Anonymous» is wrong. I’m running this behind the AWS Elastic Loadbalancer and trying the header(‘:’.$error_code. ) method mentioned above is treated as invalid HTTP.

The documentation for the header() function has the right way to implement this if you’re still on ( «HTTP/1.0 404 Not Found» );
?>

At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.

// HTTP/1.1 404 Not Found
http_response_code ( 404 );

?>

The resulting response is HTTP/1.1 404 OK

http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can’t create your own response codes using this method, however you can using the header method.

In summary — The differences between «http_response_code» and «header» for setting response codes:

1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.

2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can’t set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.

It’s not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
= http_response_code ();
$b = http_response_code ( 202 );
$c = http_response_code ();

var_dump ( $a , $b , $c );

http_response_code() does not actually send HTTP headers, it only prepares the header list to be sent later on.
So you can call http_reponse_code() to set, get and reset the HTTP response code before it gets sent.

http_response_code(500); // set the code
var_dump(headers_sent()); // check if headers are sent
http_response_code(200); // avoid a default browser page

On PHP 5.3 version, If you want to set HTTP response code. You can try this type of below trick 🙂

( ‘Temporary-Header: True’ , true , 404 );
header_remove ( ‘Temporary-Header’ );

@craig at craigfrancis dot co dot uk@ wrote the function that replaces the original. It is very usefull, but has a bug. The original http_response_code always returns the previous or current code, not the code you are setting now. Here is my fixed version. I also use $GLOBALS to store the current code, but trigger_error() instead of exit. So now, how the function will behave in the case of error lies on the error handler. Or you can change it back to exit().

if (!function_exists(‘http_response_code’)) <
function http_response_code($code = NULL) <
$prev_code = (isset($GLOBALS[‘http_response_code’]) ? $GLOBALS[‘http_response_code’] : 200);

if ($code === NULL) <
return $prev_code;
>

switch ($code) <
case 100: $text = ‘Continue’; break;
case 101: $text = ‘Switching Protocols’; break;
case 200: $text = ‘OK’; break;
case 201: $text = ‘Created’; break;
case 202: $text = ‘Accepted’; break;
case 203: $text = ‘Non-Authoritative Information’; break;
case 204: $text = ‘No Content’; break;
case 205: $text = ‘Reset Content’; break;
case 206: $text = ‘Partial Content’; break;
case 300: $text = ‘Multiple Choices’; break;
case 301: $text = ‘Moved Permanently’; break;
case 302: $text = ‘Moved Temporarily’; break;
case 303: $text = ‘See Other’; break;
case 304: $text = ‘Not Modified’; break;
case 305: $text = ‘Use Proxy’; break;
case 400: $text = ‘Bad Request’; break;
case 401: $text = ‘Unauthorized’; break;
case 402: $text = ‘Payment Required’; break;
case 403: $text = ‘Forbidden’; break;
case 404: $text = ‘Not Found’; break;
case 405: $text = ‘Method Not Allowed’; break;
case 406: $text = ‘Not Acceptable’; break;
case 407: $text = ‘Proxy Authentication Required’; break;
case 408: $text = ‘Request Time-out’; break;
case 409: $text = ‘Conflict’; break;
case 410: $text = ‘Gone’; break;
case 411: $text = ‘Length Required’; break;
case 412: $text = ‘Precondition Failed’; break;
case 413: $text = ‘Request Entity Too Large’; break;
case 414: $text = ‘Request-URI Too Large’; break;
case 415: $text = ‘Unsupported Media Type’; break;
case 500: $text = ‘Internal Server Error’; break;
case 501: $text = ‘Not Implemented’; break;
case 502: $text = ‘Bad Gateway’; break;
case 503: $text = ‘Service Unavailable’; break;
case 504: $text = ‘Gateway Time-out’; break;
case 505: $text = ‘HTTP Version not supported’; break;
default:
trigger_error(‘Unknown http status code ‘ . $code, E_USER_ERROR); // exit(‘Unknown http status code «‘ . htmlentities($code) . ‘»‘);
return $prev_code;
>

$protocol = (isset($_SERVER[‘SERVER_PROTOCOL’]) ? $_SERVER[‘SERVER_PROTOCOL’] : ‘HTTP/1.0’);
header($protocol . ‘ ‘ . $code . ‘ ‘ . $text);
$GLOBALS[‘http_response_code’] = $code;

// original function always returns the previous or current code
return $prev_code;
>
>

Источник

Оцените статью
toolgir.ru
Adblock
detector