Sorry, folks, this is one of those "I just copy/pasted a script and it doesn't work" posts. Please be kind :o

I'm trying to use the language switch script found on the following page: http://www.phpbuilder.com/tips/item.php?id=343

Here's the code:

<?php

$completeNewURL = "";

$referer = "$HTTP_REFERER ";
$brokenDownReferer = "";

if (stristr($referer, "/en/")){
	$brokenDownReferer = str_replace("/en/", "/ja/", $referer);
}else{
	$brokenDownReferer = str_replace("/ja/", "/en/", $referer);
}

//These two lines of code will redirect the user to the corresponding 
//japanese/english version of the page they were just on.

//print("$completeNewURL");
$URL="$brokenDownReferer";
header ("Location: $brokenDownReferer");

?>

I've copied the script to a text file (BBEdit on the Mac), made sure that there are no spaces before or after the <?php ... ?>, and saved the script as "language_switch.php". In the navigation menu of my site, I've made a link to this .php file, however, when I click on the link I get the following error:

Warning: Cannot modify header information - headers already sent by (output started at /home/virtual/site282/fst/var/www/html/MySiteHere.com/language_switch.php:1) in /home/virtual/site282/fst/var/www/html/MySiteHere.com/language_switch.php on line 19

I know this is a very common error, but I can't figure out why headers have already been sent -- there seems to have been no output until header().

Any ideas? Many thanks in advance!

    Hi,

    please make sure that the script begins with <?php without any empty lines, whitespaces or any other characters in front of <?php.

    Those characters are the reason for that message because they are sent to the browser before the header function call takes place.

    Thomas

      Thank you for the reply, tsinka.

      While I did not have any whitespace before the <?php, I believe that I have found my problem:

      I had been saving my .php file encoded as Unicode (UTF-8). Re-saving the file with ISO-8859-1 encoding fixed the problem -- the script now seems to work as intended.

        Some editors write a BOM (Byte-Order-Marker) at the beginning of utf-8 encoded file. Seems like PHP is interpreting that bytes not as bom but as content of the file.

        So you're right, the BOM was the problem.

        Thomas

          OOoo! Thanks for the explanation!

          I just tried saving the .php file as UTF-8 with no BOM, and the script still works. I'll change BBEdit to use that as my default file encoding from now on. Thank you very much for the insight — more than I expected!

            Write a Reply...