We save data in our DB after passing it via htmlentities method to avoid any injection attacks
And while using it back, we do html_entity_decode to get back the original value. In some cases in our code, the htmlentities is done 2-3 times on the same peice of data due to our saving techniques (hard to explain). So we basically want to avoid encoding the same strings multiple times.
Is there a good reliable way to detect if a string has been passed via htmlentities method already?
I guess one way is to check for stuff like " in the ecoded string, but anything more reliable? Any in built method that just tells me if a string is encoded or not?
We are using Laravel, maybe a helper method in there that could help us?
This is fundamentally the wrong approach IMO. Store the data raw, as it comes. While it's in the database it can't do you any harm.
Pass it through htmlentities only when you're just about to put it into a HTML document - because that's the only context in which it could be dangerous.
That will save all the encoding and decoding - you simply encode it on demand as necessary.
As mentioned by ADyson, you're handling the data incorrectly throughout your system.
Laravel's templating engine "Blade" will automatically send your variables through htmlspecialchars() to prevent XSS attacks.
From the documentation:
Blade
{{ }}statements are automatically sent through PHP'shtmlspecialcharsfunction to prevent XSS attacks.
This will protect your site from potential XSS attacks, without you needing to encode/decode your data as you run INSERT/SELECT queries against your database.
Provided you're using Laravel's built-in DB Builder / Eloquent, your SQL queries are also protected automatically:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.