[PHP][JavaScript] Encoding and Character Garbling Issues with urlencode and encodeURI

Tadashi Shigeoka ·  Wed, October 19, 2011

Character garbling issues occurred in IE depending on when encoding happens in PHP and JavaScript.

The solution was to not encode on the PHP side and pass it to JavaScript, but instead pass the value as is from PHP and encode it on the JavaScript side.

■ Pattern That Causes Character Garbling Issues

[PHP]

Encode with urlencode in the controller and output to the template.

$url = urlencode('http://example.com/?p=2&keyword=テスト');
$smarty->assign('url', $url);

[HTML]

Next

[JavaScript]

function formsubmitt (action_url) {
    form.action = action_url;
    form.submit();
}

■ Pattern That Works Properly Even in IE

[PHP]

Don’t encode in the controller, pass as is to the template.

$url = 'http://example.com/?p=2&keyword=テスト';
$smarty->assign('url', $url);

[HTML]

Next

[JavaScript]

function formsubmitt (action_url) {
    form.action = encodeURI(action_url);
    form.submit();
}

That’s all.

【Reference】

javascript: escape(), encodeURI(), encodeURIComponent() 比較 (groundwalker.com) (javascript: escape(), encodeURI(), encodeURIComponent() Comparison (groundwalker.com))

URL(URI)エンコード・デコードを行う - JavaScript TIPSふぁくとりー (Performing URL (URI) Encode/Decode - JavaScript TIPS Factory)

PHP: urlencode - Manual

That’s all from the Gemba.