PHP language selector - php

I'm pretty sure this was working before, so I don't know what happened to the code I had in place for a language selector I've been using for a site in development. Here is the php:
<?php
session_start();
if(isset($_POST['language'])) {
$_SESSION['language'] = $_POST['language'];
}
$language = (isset($_SESSION['language']) ? $_SESSION['language'] : "english");
include('/Languages/'.$language.'.php');
?>
The HTML:
<form method="post">
<input type="image" name="language" value="english" src="Images/english.png"/>
<input type="image" name="language" value="spanish" src="Images/spanish.png"/>
...
</form>
The PHP in each 'dictionary' file:
<?php
$content = array(
"identifier1"=>'content with html to be included',
"identifier2"=>'more content to be included'
);
?>
And finally, the code on the actual page to call the right language:
<?php echo $content['identifier1']; ?>
So this is supposed to work by having the user click one of the images in the form. The form sends the value of the clicked image, which is the name of the language file that should be opened. The PHP, which is in the head of the page, then takes this value, and includes the dictionary file (eg, english.php), which can then be referred to in the HTML from the echo above.
However, I cannot get this to work. When I click on the image, the page reloads. I've tried doing a <?php echo 'stuff'; ?>, and that works, so my PHP should be working. This means that something must be wrong with the code.

Okay, apologies for taking so long to reply. It took me a while to do some further research into this, along with other links provided here by others. In any case, I found a better solution which uses cookies instead of a single session as follows:
Before beginning your HTML (or at the very least, before your body tag), add the following PHP code:
<?php
$lang = "YOUR DEFAULT LANGUAGE";
$allowedlangs = array(
"AVAILABLE LANGUAGES 1",
"AVAILABLE LANGUAGESS 2"
);
if (!empty($_GET["lang"])) {
$rlang = $_GET["lang"];
} else if (!empty($_COOKIE["lang"])) {
$rlang = $_COOKIE["lang"];
}
if (isset($rlang) && !empty($rlang) && in_array($rlang, $allowedlangs)) {
$lang = $rlang;
setcookie("lang", $lang,time()+31536000);
}
$langmaps = array(
"AVAILABLE LANGUAGES 1" => "FILE PATH TO LANGUAGE 1 FILE.php",
"AVAILABLE LANGUAGES 2" => "FILE PATH TO LANGUAGE 1 FILE.php"
);
include($langmaps[$lang]);
?>
So $lang is a variable that initially defines the language you want a new visitor to see. That is, the default language. Whatever value $lang takes, it must be from the array on the next line. It doesn't matter what you call your languages, as long as you can identify them for yourself. The code doesn't care. Call the English language "english", "en", "lang1", "TeaAndCrumpets", or anything you want. Make a new line for each additional language you want to have.
Further down you have the line with $langmaps. The lines in this array will match the names of your languages to the file path that contains your language values. For example, if your English language is "TeaAndCrumpets", the code would be:
"TeaAndCrumpets" => "FILE PATH TO LANGUAGE 1 FILE.php"
Then just type in the file path to the English file, which, again, can be named anything, as long as you point to the right file.
After this, you just need the buttons. No forms needed. Just an for each language you want. In this case, I use images wrapped in tags like so:
<img src="/images/english.png" title="English" alt="English">
<img src="/images/russian.png" title="Russian" alt="Russian">
This will simply add the URL variable to the address bar, and the PHP kicks in. Make sure whatever value in the href you have for the lang variable matches one of the names in your $allowedlangs array, and that your title and alt attributes make sense to your visitors.

Ok, a couple of things:
1) Why are you using an associative array for something that is innherently an indexed system? Why not use a regular array?
2) Try debugging. Echo $_SESSION['language'] and make sure the value is even making it through.
Also, try doing a var_dump($content) and see what that gives you after you've included the language file.
Updates:
Add an action to your form. Even if it's empty. That could be having an effect.
Did you try a var_dump on your $_POST value?
Also, try
var_dump("/Languages".$language.".php");
However, I would specify the location of your language file via a base directory. Usually in projects I have a global application object store that value as a constant like this:
define("BASEDIR", __DIR__ . "/");
You would, of course, add the appropriate number of "../" or additional filepath information to the end of that if necessary.
From there, I use that as the "base directory" for ALL file includes. So, if your language file is at
[base project directory]/Languages/english.php
then you'd include it like so:
include(BASEDIR . "Languages/" . $language . ".php");
Of course, make sure that your base dir constant has a trailing slash, or add one here (I prefer terminating all directory names with a trailing slash).

Related

How to use $_GET variable (index.php?cat=about)

I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.
So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.
About Us
I've also made cat.php file but what next?
In your index.php file you can use the following:
if(isset($_GET['cat']) { // means if the user use the url with ?cat=something
echo "<1>About {$_GET['cat']}</h1>"; //print the about of the cat as html
}
OK, Suppose you've two PHP files. page_a.php & page_b.php.
page_a.php
<?php
echo "<a href='page_b.php?cat=about'>Click Me</a>";
page_b.php
<?php
print_r($_GET); // Show all GET contents
echo $_GET['cat']; // Show what content exist in 'cat' part of url
Hope, this will clear your doubt of how to send data in url from one page to another using GET mehtod.
To store variable data in the url, you can use the query string. This is the portion of the url that immediately follows the protocol, domain name and file path
The query string begins with ? and may contain one or more parameter parameter value pairs. The parameter and parameter value are separated by =. Each pair is separated by &.
Let's suppose you do development for a tourism company called Gi Tours which provides content in 3 different languages. Because site visitors will want to be able to select their preferred language, you can provide flag images that will indicate a certain language and wrap those flags with the appropriate hyperlinks. Rather than writing out the full language name, you can simply assign id numbers to represent each like this:
<?php
echo "<img src=\"img/ge.png\">";
echo "<img src=\"img/en.png\">";
echo "<img src=\"img/ru.png\">";
?>
If a visitor clicks the second flag which loads this url: https://www.gitours.ge/index.php?lang=2, your index.php code can be written to extract the value assigned to lang by using $_GET["lang"].
If you write in your index.php file:
<?php
echo $_GET["lang"];
?>
Your code will display:
2
Or on your index.php file, you can easily generate dynamic page content using $_GET array data.
<?php
if(isset($_GET["lang"])){ // this checks if lang exists as a parameter in the url
$lang=$_GET["lang"]){ // $lang will equal the value that follows lang=
}else{
$lang=1; // if there was no lang parameter, this sets the default value to 1
}
if($lang==2){
// show English content
}elseif($lang==3){
// show Russian content
}else{
// show Georgian content
}
?>
This is, of course, a simplified demonstration; other techniques can be used to interact with the $lang value.
#Lasha Palelashvili let suppose below example:
above you are sending only one input parameter cat through url to the index.php file at server side so when you send this data from url it will send by get method by default, if you want to get this url info(input parameter) at the php side so $_GET will help you to fetch that info $_GET is actually an array which stores your input parameter as key and input parameter's value as value for your case("index.php?cat=about") $_GET array will contain value like below:
$_GET = array("cat" => "about")
now at the server side you can easily get the value like:
//index.php
<?php
$cat = $_GET["cat"];
echo $cat;
?>

How to test a file with IF and a variable from another file with PHP and HTML

I want to be able to enter something in a <form>, then in another php file check to see if the thing I put down exists.
Lets say I put in the text box "Jilly"
I want it to detect "Jilly.txt"
This is my code
File#1.php:
<form action="File#2.php" method="post">
<input name="user" type="text">
<input type="submit" value="Go">
File #2:
<?php
$user = $_POST["user"]
if (bool file_exists ( string $user )) {
echo . $user . " filename exists."
}
else {
echo . $user . " filename doesn't exist."
}
?>
So what am I doing wrong? When I click the "Go" input, it shows file#2 a blank file, so it there is something wrong with file#2's PHP code.
Welcome to php.
You're clearly reading documentation. Good job! Just understand that datatypes are information solely for the reader of the documentation and are not written out in the actual script.
Therefore change,
if (bool file_exists ( string $user )) {
to
if (file_exists ( $user . "txt" )) {
you probably did this because
bool file_exists ( string $filename )
is the way the function is written in the documentation. However, the first line is always just a very short reference, explaining all the datatypes. To see actual syntax, scroll down to examples. (Assuming you're reading on php.net)
Bool is the 'return type' - writing that down doesn't have any meaning and thus leads to an error. I also concatenated ".txt" so it checks for the file Jilly.txt rather than the file Jilly.
Your echos alsso aren't quite right. Write it like this:
echo $user . " filename exists.";
So remove the dot immediatly after the echo. The dot "concatenates" two strings, so it needs to have one string to the left and one to the right. A semicolon is also important.
And at last, change the file name so it doesn't contain a # anymore.
There are multiple errors. The first one is, that a hash # is not allowed as part of a directory or file name in an URL. As written in the comments, the part after a hash is used as in-page anchor, to jump to a specific section.
For the next point refer to the answer of #KjeldSchmidt.

Showing a href without needing to input text(Wordpress and html issue)

I'm on wordpress atm and I'm stuck with a small issue.
To save the people receiving the site some work I hoped i'd be able to make things as easy as possible.
So what I did was add a plugin called "advanced custom fields", and I made a custom field.
What I wanted was to have 1 custom field that'd show a link(as text) in the following way:
The issue
My issue is that I want the link(example) to show without needing to fill in "The issue", because in the backend(the wordpress cms) it's a lot of trouble for the person to fill in an extra sub field called name with the exact same value.
So my question is, is it possible to show a link without needing to fill in "The Issue" or is there a different html tag for this?
Thanks in advance!
You can check if the field "The Issue" is empty and only in this case reprint in this place the "example" field.
if (!empty(the_field('The issue'))) {
<?php the_field('The issue'); ?>
} else {
<?php the_field('example'); ?>
}
If you need to ensure that a link input from the user is external (that always begins with http://) you can do something like this (of course, before printing the $link variable in the href):
if (strpos($x, "http://") == 0) {
$link = $x;
} else {
$link = "http://" . $x;
}
strpos search the position of the first occurrence of a substring on your string ($x, for example). So if the position is 0 means that the string begins with "http://", so it is external, but if this is not the case you have to add it at the beggining of the string.
One have to note that user inputs are tricky (imagine that the user writes " http: //..." with a space before the url) so it is possible that one needs more validation than this, but I think that the idea is clear.

Turning a form's GET into a PHP variable?

I'm trying to make the following form's GET function to be part of a predefined variable.
Any ideas? Thanks in advance!
Let me explain a little more of what I'm really trying to do. I currently run a website concentrating on the U.S. stock market. I've created an HTML form with a method=GET. This form is used like a search box to look up stock ticker symbols. With the GET method, it places the ticker symbol at the end of the URL, and I created a quotes.php page that captures this information and displays a stock chart based on what ticker symbol is keyed into the box. For the company names, I've created a page called company.php that declares all of the variables for the company names (which happens to be a $ followed by the ticker symbol). The file, company.php, is the only file included in quotes.php.
This is where this came in: ' . $$_GET["symbol"] . '
The above code changes the GET into the variable based on what was typed into the form. I've used "die" to display an error message if someone types something into the box that doesn't match a variable in the company.php page.
I've also added into the company.php page variables for each company that will display which stock exchange each stock is listed on. These variables begin with "$ex_". So, what I was trying to do was have the symbol keyed into the box appended to "$ex_" so that it would display the corresponding stock exchange.
My questions are:
Is there a way to have what is typed into the form added to "$ex_"?
Is this an insecure way to code something like this (can it be hacked)?
Thank you all!
Rather than prefixing your variables and using variable variables (that are potentially insecure especially with user input), try this:
$ex = array(
"foo" => "bar",
...
);
if( !isset($ex[$_GET['symbol']])) die("Error: That symbol doesn't exist!");
$chosen = $ex[$_GET['symbol']];
Here's another approach:
extract($_GET, EXTR_PREFIX_ALL, "ex");
Although it's better to use it like this just to make sure there is no security issues.
extract($_GET, EXTR_SKIP);
PHP's extract() does what exactly what you want, and you should specify "ex_" as the prefix you want.
However, there are security issues and unintended consequences to using such a function blindly, so read up on the additional paragraphs following the function parameters.
Will the below achieve what you need?
$myGetVariable = $_GET['symbol'];
$ex_{$myGetVariable} = "Something";
$_GET['symbol'] = 'APPL';
if (!empty($_GET)) {
foreach ($_GET as $k => $v) {
$var = 'ex_'.$k ;
$$var=$v;
}
}
var_dump($ex_symbol);
APPL

Switching languages on a website with PHP

I'm just looking for some advice. I'm creating a website that offers (at least) 2 languages.
The way I'm setting it up is by using XML files for the language, PHP to retrieve the values in the XML nodes.
Say you have any XML file, being loaded as follows:
<?php
$lang = "en";
$xmlFile = simplexml_load_file("$lang/main.xml");
?>
Once the file contents are available, I just output each node into an HTML tag like so:
<li><?php echo $xmlFile->navigation->home; ?></li>
which in turn is equal to : <li>Home</li>
as a nav bar link.
Now, the way in which I'm switching languages is by changing the value of the "$lang" variable, through a "$_POST", like so:
if(isset($_POST['es'])){
$lang = "es";
}elseif(isset($_POST['en'])){
$lang = "en";
}
The value of the "$lang" variable is reset and the new file is loaded, loading as well all the new nodes from the new XML file, hence changing the language.
I'm just wondering if there is another way to reset the "$lang" variable using something else, other than "$_POST" or "$_GET". I don't want to use query string either.
I know I could use JavaScript or jQuery to achieve this, but I'd like to make the site not too dependable on JavaScript.
I'd appreciate any ideas or advice.
Thanks
I would go for session variable.
At the beginning of your pages you'll have:
if (!isset($_SESSION['language']))
$_SESSION['language'] = "en";
Then you'll have some links to change the language
Español
Français
Changelanguage.php simply is something like
$language = $_GET['lang'];
// DO SOME CHECK HERE TO ENSURE A CORRECT LANGUAGE HAS BEEN PASSED
// OTHERWISE REVERT TO DEFAULT
$_SESSION['language'] = $language;
header("Location:index.php"); // Or wherever you want to redirect
Have you thought about using $_SERVER["HTTP_ACCEPT_LANGUAGE"]? Something like this:
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"]) {
$langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
for ($i = 0; $i < count($langs); $i++) {
if ($langs[$i] == "en") {
$lang = "en";
break;
}
elseif($langs[$i] == "es") {
$lang = "es";
break;
}
}
}
Of course, a switch statement might fit a bit better here, and there's more ways to say English than only en, but this should work without the user having to do a thing. If they manually change, store it in a cookie as per Ben's answer.
The most common way would be to use it as part of the url and extract it when a page loads:
http://www.your-site.com/en/somepage
Are you using a framework?
The most common way to pass a language identifier is subdomain.
http://en.wikipedia.com/
both subdomains should point to the same directory and actual language can be easily extracted from the HTTP_HOST
and for storing language files the solution is gettext

Categories