Search code examples
phpspecial-charactershtml-entities

PHP: Using html_entities correctly. Want all/any characters to be returned in error message


I'm having trouble returning certain characters in my error message. The setup is as follows:

Whatever the user enters into the textfield (if incorrect), should be returned in the error message. Whether it's a letter, a comma, an ampersand...anything. It seems html_entities or special_chars would be appropriate here.

The following block of code is where I think this idea should be set up. The following characters return a blank error message with just the string (is not a valid 4-letter ICAO airport code) attached:

+ " ' &

This is the code in question. The commented out $error_str is what I'm trying to get working.

 else
 {
   //VERIFY ICAO IS IN AIRPORTS.DB
   $airport_query = "SELECT COUNT(*) AS airport_count, LAT, LONG, IATA, Name FROM airports WHERE ICAO = '$icao'";
   $airport_result = $airports_db->queryDB($airport_query);
   foreach($airport_result as $airport_row) {}
     if($airport_row["airport_count"] == 0)
     {
       $error_str = "$icao is not a valid 4-letter ICAO airport code.";
       /* $error_str =  "html_entities($icao) is not a valid 4-letter ICAO airport code."; */     
     }

     $return_array["ICAO"] = $icao;
     $return_array["IATA"] = $airport_row["IATA"];
     $return_array["airport_name"] = $airport_row["Name"];
 }

 $return_array["error"] = $error_str;

 echo json_encode($return_array);  

Also notice the echo json_encode at the bottom. I'm not sure if I should be doing the html_entities on the $error_str or the $return_array.

Any input is appreciated.


Solution

  • There are two main issues here. The first is that the PHP function is htmlentities without an underscore in the name, and the second is that the function call can't be in a string.

    This will work:

    $error_str = htmlentities($icao) . ' is not a valid 4-letter ICAO airport code.';
    

    htmlentities accepts a string, so running it on $return_array will not work. You could do htmlentities($error_str) before putting it in the $return_array.

    http://www.php.net/manual/en/function.htmlentities.php