?
Solved

Correct programming

Posted on 2005-03-14
7
Medium Priority
?
222 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
This article discusses how to implement server side field validation and display customized error messages to the client.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

762 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