PHP URL encoding special characters fails

Viewed 42

I moved my website to a new host. It has links (both internal and external from other websites I don't manage) with accents in the URLs which stopped working. Apparently the site used ISO-8859-1 and the new host UTF-8 I'm trying to solve this problem with PHP.

Example of the word "condición" in links looks like:

condici%F3n

That returns a 404 but if I write

condici%C3%B3n

OR

condición

on the address bar, it works fine.

So far I managed to print the right URL with the following code:

<?php
mb_internal_encoding("iso-8859-1");
mb_http_output( "iso-8859-1" );
ob_start("mb_output_handler");
$value  = $_GET['termino'];
echo $value;
?>
https://example.com/page.php?termino=condici%F3n
  • Prints condición

The problem comes when I try to pass that word and redirect to an URL

<?php
mb_internal_encoding("iso-8859-1");
mb_http_output( "iso-8859-1" );
ob_start("mb_output_handler");
$value  = $_GET['termino'];
header("Location: https://example.com/$value", true, 301);
?>

It switches back to:

condici%F3n

Why is this happening? How can I solve this?

1 Answers
<?php
   mb_internal_encoding("iso-8859-1");
   mb_http_output( "iso-8859-1" );
   ob_start("mb_output_handler");
   $value  = urlencode($_GET['termino']);
   header("Location: https://example.com/$value", true, 301);
?>

And Now print with urldecode()

<?php
     echo urldecode($_GET['value'];
?>
Related