Question

I'm having an issue when trying to save strings with accents.

Our online system is used by clients from different countries, so some of our clients use accents.

When doing a request to get the value to save like this

$value = trim(strip_tags(htmlspecialchars($_REQUEST['value'], ENT_QUOTES, 'UTF-8')));

It saves the value in this way

Gé

If instead of htmlspecialchars I use htmlentities it saves like this

géî

The correct string I'm trying to save is

I need this to be saved correctly so it can be displayed correctly on screens and reports.

Our db uses UTF-16 (MS SQL Server), and I'm declaring the meta tags to use UTF-8 on the page like this

<meta charset='utf-8'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>

This is how the connection looks:

$link = sqlsrv_connect($dbserver, array(
    'Database'=>$database,
    'UID' => $uid,
    'PWD' => $pwd,
    'CharacterSet' => 'UTF-8'
));
Was it helpful?

Solution

After some trial and error, this is the solution I've found.

sqlsrv_connect does by default a connection pooling, so the connection remains in the application pool.

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the "ConnectionPooling" option in the $connectionOptions array to 0 (or FALSE). For more information, see » SQLSRV Connection Pooling.

From PHP Manual - sqlsrv_connect

My connection used to be like this

$link = sqlsrv_connect($dbserver, array(
    'Database'=>$database,
    'UID' => $uid,
    'PWD' => $pwd
));

Without the characterset.

Even after I added the characterset to the connection, I still experienced this errors.

This is my connection now.

$link = sqlsrv_connect($dbserver, array(
    'Database'=>$database,
    'UID' => $uid,
    'PWD' => $pwd,
    'CharacterSet' => 'UTF-8'
));

After I forced the browser to use UTF-8 by using the meta tags it was saving correctly to the db but displaying incorrectly. This was because I was encoding to UTF-8 twice, I then removed the second encoding when displaying.

After all this I did an IIS Reset to reset the application pool, and forced on the scripts to close the connection after processing like this:

// Close the connection.
sqlsrv_close( $linkEventlogic );

It now works correctly.

OTHER TIPS

Your way looks good, try:

$string = "\* this is test string *\";
echo utf8_encode($string);

Works?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top