?
Solved

Correct programming

Posted on 2005-03-14
7
Medium Priority
?
223 Views
Last Modified: 2008-03-17
Dear Expert

I have a PHP code that simply selects user's language and leave a cookie for next visit. So customer will not select his language every time he visits the page.

 I wrote the following program and it's working properly. My problem is I had to use some of codes both at if and else. One of them is not necessary but I couldn't find the solution to remove one of it and get it worked properly. If you could please write me the correct programming for this, it will be appreciated.

Kind regards


<? ob_start();

$array_lang = array(0=>"English", 1=>"Turkish", 2=>"Greek");
$array_lang_pro = count($array_lang);
if(isset($_GET[language])) {
  setcookie("language", $_GET[language], time() + 31536000);
  ?>
  <form method="GET" name="form" action="cookie2.php">
  <?
  echo "<select name=\"language\" onChange=\"this.form.submit()\">";
  echo "<option value=\"\">Select...</option>";
 
  for ($j = 0; $j < $array_lang_pro; $j++){
      if($_GET[language] == $array_lang[$j]) {
            print("<option value=\"$array_lang[$j]\" selected>$array_lang[$j]");
      }
      else {
            print("<option value=\"$array_lang[$j]\">$array_lang[$j]");
      }
  }
  echo"</select>";
  ?>
  </form>
  <?
}
else{
  ?>
  <form method="GET" name="form" action="cookie2.php">
  <?
  echo "<select name=\"language\" onChange=\"this.form.submit()\">";
  echo "<option value=\"\">Select...</option>";

  for ($j = 0; $j < $array_lang_pro; $j++){
    if($_COOKIE[language] == $array_lang[$j]) {
          print("<option value=\"$array_lang[$j]\" selected>$array_lang[$j]");
      }
      else {
         print("<option value=\"$array_lang[$j]\">$array_lang[$j]");
      }
  }
  echo"</select>";
}
?>
</form>
0
Comment
Question by:hasozduru
  • 4
  • 2
7 Comments
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13541235
<?php

ob_start();

$array_lang = array(0=>"English", 1=>"Turkish", 2=>"Greek");
$array_lang_pro = count($array_lang);

if(isset($_GET["language"])) {
  setcookie("language", "{$_GET['language']}", time() + 31536000);
}

$get_language = (isset($_COOKIE["language"])) ? $_COOKIE["language"] : "";
$get_language = (isset($_GET["language"])) ? $_GET["language"] : $get_language;

?>

  <form method="GET" name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<?php
  echo "<select name=\"language\" onChange=\"this.form.submit()\">";
  echo "<option value=\"\">Select...</option>";
  for ($j = 0; $j < $array_lang_pro; $j++){
     $selected = ($get_language == $array_lang[$j]) ? "selected=\"selected\"" : "";
     print("<option value=\"$array_lang[$j]\" $selected>$array_lang[$j]</option>");
  }
  echo"</select>";
?>

  </form>
0
 

Author Comment

by:hasozduru
ID: 13541408
Hi there

Thank you for your answer. I have one more issue. If you swap the following lines, program works one step back. Could you please explain me the reason?


$get_language = (isset($_GET["language"])) ? $_GET["language"] : $get_language;
$get_language = (isset($_COOKIE["language"])) ? $_COOKIE["language"] : "";

Thanks
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13541438
That is a short way of writing IF.. ELSE.. loop.

I put cookie condition is first because the GET value should overlap the COOKIE data. In detail :

$get_language = (isset($_COOKIE["language"])) ? $_COOKIE["language"] : "";

==> first checks if cookie is present. if it is $get_language is assigned to cookie value.

$get_language = (isset($_GET["language"])) ? $_GET["language"] : $get_language;

==> then checks if there is a GET variable for the "language" form-data.
***** Even if "language" cookie is found and $get_language is set to the cookie data, if a GET value is set, the value of $get_language will be replaced with that "get" value.*****

If you swap the lines, there will be no value for $get_language if cookie is not set. If you have a GET variable for "language", you should be able to display that value in the selection box.

Hence the reason. :=/
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:hasozduru
ID: 13541500
Hi

I understood the most of it but I couldn't this part. This one...

if(isset($_GET["language"])) {
  setcookie("language", "{$_GET['language']}", time() + 31536000);
}

... is always working when you change the select box. Let say cookie is assigned and get is performed. When we write ...

setcookie("language", "{$_GET['language']}", time() + 31536000);

... in every condition language will be selection. So actually order of following two lines should not matter

$get_language = (isset($_GET["language"])) ? $_GET["language"] : $get_language;
$get_language = (isset($_COOKIE["language"])) ? $_COOKIE["language"] : "";

$_GET["language"] and $_COOKIE["language"] will be equal to Greek for instance so $get_language will be Greek for both lines. How come when "setcookie("language", "{$_GET['language']}", time() + 31536000);" line runs and $_COOKIE["language"] does not change and it changes after next selection?

Thanks
0
 
LVL 32

Accepted Solution

by:
ldbkutty earned 1500 total points
ID: 13541509
Yes, the "problem" is cookie could not be retrieved sometimes when called and used in the same page.. You'll get the correct result by refreshing or re-opening the browser window.
0
 
LVL 25

Expert Comment

by:Marcus Bointon
ID: 13542845
The first time a visitor hits your site, they don't have a cookie set telling you which language to use. In the code presented so far, you're just assuming that they can speak enough English to be able to select their real language. A much nicer approach is to ask their browser, as it tells you what languages they prefer, in what order. The functions below let you use that info. The other change that I'd suggest (and it's required by these functions) is to use the excellent ISO 639-1 standard for language codes instead of your made-up values, as it is used everywhere on the web.

$array_lang = array('en' => 'English', 'tr' => 'Turkish', 'el' => 'Greek');

To use them in your code, just change this one line:

$get_language = (isset($_COOKIE["language"])) ? $_COOKIE["language"] : bestLanguage(browserlanguages(), array_keys($array_lang));

This says: if no language cookie is set, pick the language that we offer that their browser likes most.

/**
* Parse an HTTP_ACCEPT_LANGUAGE header string into a simple list of languages with locale info removed
*/
function browserLanguages() {
      $langcodes = array();
      if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
            $languages = explode(',' , $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            foreach($languages as $language) {
                  $langparts = explode(';', $language);
                  $langcodeparts = explode('-', $langparts[0]); //Convert en-us to en etc
                  $langcode = trim($langcodeparts[0]);
                  if (!in_array($langcode, $langcodes)) //Not already listed
                        $langcodes[] = $langcode;
            }
      }
      return $langcodes;
}

/**
* Pick the best available language to deliver to a browser
* @param array $browserlanguages List of languages supported by the browser - see {@link browserLanguages()}
* @param array $availablelanguages List of the languages that you support, default one first
*/
function bestLanguage($browserlanguages, $availablelanguages) {
      foreach($browserlanguages as $browserlanguage) {
            if (in_array($browserlanguage, $availablelanguages))
                  return $browserlanguage;
      }
      //Nothing found matching browser pref, so find default
      if (count($availablelanguages) > 0)
            return $availablelanguages[0];
      else
            return 'en'; //Not a lot else we can do here
}
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13542990
Enlightening suggestion. Apart from the author, its more useful for me :)

Squinky, Can you have a look here : http:Q_21350941.html

I never had chance to parse .shtml file as php ( also I am not in a testing environment now ). Your suggestion would be of great input.
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

612 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question