The message for class “Exception” causes PHP Fatal Error

87
February 09, 2019, at 04:00 AM

After execute this simple code:

$message = 'some text '.inet_pton('119.252.33.171');
throw new \Exception($message);

PHP returns Fatal Error

Fatal error</b>: in ...

This code is expected to return

Fatal error: Uncaught Exception: ..

But this is not happening. With this message, the error occurs in the class "Exception"!

Code example 1 from sandbox.onlinephpfunctions.com (comment and uncomment 2 lines of code 3-4 and 6-7)

Code example 2 from sandbox.onlinephpfunctions.com

This behavior is noticed when converting many other IPs. At the moment I solved the problem with the following line before "throw new":

$message = preg_replace( '/[^[:print:]\r\n]/', '_', $message);

How to properly escape characters in message for Exception or it is PHP bug?

My PHP version is 7.2

Answer 1

That would be because inet_pton() is not meant to ouput strings, but bytes in network order (I don't remember if it's little endian or big endian).

Exception messages are not meant to include bytes, but printable characters. You can, however, put pure bytes into strings. These are then decoded to (probably) UTF-8 or other encoding to display readable text.

The following code

$message = inet_pton('119.252.33.171');
var_dump($message);
for($i = 0; $i < strlen($message); $i++)
{
   echo ord($message[$i]) . "\n";
}

Produces

string(4) "w�!�"
119
252
33
171

Compare these two lines

throw new \Exception(chr(33)); // Displays stacktrace
throw new \Exception(chr(252)); // Fails to output

My guess would be that an error occurs while PHP is trying to format the string as UTF-8 to print the exception message to stdout, but invalid UTF-8 string is passed in and the write/decoding fails.

Either way, seems like a bug in PHP.

Rent Charter Buses Company
READ ALSO
How to create OnGuard license key generation equivalent in PHP

How to create OnGuard license key generation equivalent in PHP

I need to generate the license key same way like how OnGuard generates but using phpThis is the OnGuard http://wiki

135
Set date to year in existing column

Set date to year in existing column

Hello there I am trying to update an existing column and set the year column from 1/1/2019 to just 2019I am getting a syntax error not sure how to do this

145
Creating a SQL server view from multiple DB engines?

Creating a SQL server view from multiple DB engines?

I have a SQL server DB, a Oracle DB, a MySQL DBI have a way to join the tables from each DB

126
SQL : Obtaining groups and counts at the same time

SQL : Obtaining groups and counts at the same time

Suppose my table looks like this:

128