I'm having a 2 issues with my website.
It's a multi language one (german, english).
I always kept the translations in an XML document like this
<?xml version="1.0" encoding="utf-8"?>
<root>
<les>
<en>Lesson</en>
<de>Lektion</de>
</les>
Then I converted those XML vars into php ones and echo'd them where needed like this
$xml=simplexml_load_file("langindex.xml") or die("xml not found!");
$les = $xml->les->$lang;
<?php echo $les;?>
Problem 1 is that no language is set as default when I open the Website so I always have to select a language first, even though I included that !isset. If I don't select anything, some images will be streched and it gives me the error that no language is set.
<?php
session_start();
$page = 0;
$lang = $_GET['lang'];
$langArray = array('en','de');
$found = false;
if(in_array($lang, $langArray))
$found = true;
if(!$found)
$lang = 'en';
if(!isset($_SESSION['lang']))
$_SESSION['lang'] = 'en';
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'de')))
$_SESSION['lang'] = $_GET['lang'];
include '../nihongo/php/dbconnect.php';
My language switch works with a simple <a href="?lang=X"> and that ?lang=X will be shown in the URL as well.
Enough of that.
Since XML is pretty inpractical I wanted to switch the whole thing up to an SQL database.
I've created a table with the columns ID, german and english and connected the db sucessfully.
Now I want PHP to tell SQL to get only the text of the session language with a select like this for example.
SELECT german FROM texts WHERE ID = '1'
SELECT english FROM texts WHERE ID = '2'
My problem is that I really don't know how to do that with PHP.
I would think that I'd either have to throw a PHP var into the statement somehow, or select the whole row and let PHP decide which one should be displayed.
Every advice/suggestion is welcome!
Thanks in advance!
I like the way OpenCart implemented this, because it's simple and doesn't add additional calls to the DB. Take a look at their implementation. You learn a lot investigating and learning from Open Source projects.
They have a php script per language and module with an array that contains all the strings. It just include or load the scripts to get access to the strings, for example: en-gb. Loading a string by its key with this method:
language->get('heading_title');
Related
Just a small question for anyone out there that uses smarty. I am trying to pass PHP directly into my code, but when I do, the cached version cuts out the PHP and just prints it directly like so.
<div class="dashboard-card-content">
<?php
$con = mysqli_connect(Nice,Try,Fly,Guy);
$company_id = $_smarty_tpl->tpl_vars['auth']->value['user_id'];
$company_id = mysqli_query($con,"SELECT company_id FROM cscart_users WHERE user_id = $company_id")->fetch_object()->company_id;
$company_id = mysqli_query($con,"SELECT goal FROM cscart_companies WHERE company_id = $company_id")->fetch_object()->goal;
echo "Your current goal is: ".$company_id;
?>
This just prints all of it out on my webpage, so I tried using the following:
{Literal}
{Include_php}
{php}
And I just can't find a way to get my PHP code to go into my TPL how I want it. This is becoming really frustrating and all I want is for my cache files to leave the PHP code alone. Sorry if this is a dumb question but I have been researching this for a while. How do I implement SmartyBC so that I can still use PHP injections. And if using SmartyBC is a bad idea, can someone give me a dumbed down version of how to use a seperate PHP function page to set variables to show in the Template?
Smarty is a template engine for presentation logic only. You cannot put application logic inside a template. It was possible in older versions of Smarty but fortunately not anymore. Just execute those funcions in a php file and pass the result to the template.
And yes, you can use SmartyBC: http://www.smarty.net/docs/en/bc.tpl, but that's supposed to be used for compatibility with existing projects. It's a really bad idea and shouldn't be used for new projects.
Why do you want to use php in Smarty?
Put your logic into a class or function, and pass the data via the controller: Registry::get('view')->assign('smarty_variable', $data), and you are good to go.
You can create PHP function which gets necessary data from database. E.g.
function fn_get_company_goal($user_id)
{
$company_id = db_get_field("SELECT company_id FROM ?:users WHERE user_id = ?i, $user_id");
$goal = db_get_field("SELECT goal FROM ?:companies WHERE company_id = ?i, $company_id");
return $goal;
}
Put it to your addon. Then you can use it in the Smarty template in the following manner:
{$goal = $user_id|fn_get_company_goal}
for security reasons we need to disable a php/mysql for a non-profit site as it has a lot of vulnerabilities. It's a small site so we want to just rebuild the site without database and bypass the vulnerability of an admin page.
The website just needs to stay alive and remain dormant. We do not need to keep updating the site in future so we're looking for a static-ish design.
Our current URL structure is such that it has query strings in the url which fetches values from the database.
e.g. artist.php?id=2
I'm looking for a easy and quick way change artist.php so instead of fetching values from a database it would just include data from a flat html file so.
artist.php?id=1 = fetch data from /artist/1.html
artist.php?id=2 = fetch data from /artist/2.html
artist.php?id=3 = fetch data from /artist/3.html
artist.php?id=4 = fetch data from /artist/4.html
artist.php?id=5 = fetch data from /artist/5.html
The reason for doing it this way is that we need to preserve the URL structure for SEO purposes. So I do not want to use the html files for the public.
What basic php code would I need to achieve this?
To do it exactly as you ask would be like this:
$id = intval($_GET['id']);
$page = file_get_contents("/artist/$id.html");
In case $id === 0 there was something else besides numbers in the query parameter. You could also have the artist information in an array:
// datafile.php
return array(
1 => "Artist 1 is this and that",
2 => "Artist 2..."
)
And then in your artist.php
$data = include('datafile.php');
if (array_key_exists($_GET['id'], $data)) {
$page = $data[$_GET['id']];
} else {
// 404
}
HTML isn't your best option, but its cousin is THE BEST for static data files.
Let me introduce you to XML! (documentation to PHP parser)
XML is similar to HTML as structure, but it's made to store data rather than webpages.
If instead your html pages are already completed and you just need to serve them, you can use the url rewriting from your webserver (if you're using Apache, see mod_rewrite)
At last, a pure PHP solution (which I don't recommend)
<?php
//protect from displaying unwanted webpages or other vulnerabilities:
//we NEVER trust user input, and we NEVER use it directly without checking it up.
$valid_ids = array(1,2,3,4,5 /*etc*/);
if(in_array($_REQUEST['id'])){
$id = $_REQUEST['id'];
} else {
echo "missing artist!"; die;
}
//read the html file
$html_page = file_get_contents("/artist/$id.html");
//display the html file
echo $html_page;
I've searched far and wide and every CMS tutorial out there either doesn't explain this at all or gives you a huge chunk of code without explaining how it works. Even on stack overflow I can't find anything close to the answer, though I'd be okay with eating my words if someone could point me to the answer.
I am using PHP and mysql for this project.
I am building a CMS. Its extremely simple and I understand every concept I think I'll need except how to dynamically generate pages and page links. The way I want to do it is by having a database table that stores the name of a page and the main content of the page. That's all. Then I'd just call a script to pull the main content of a page into whatever page I happen to call. No big deal, right? Wrong.
Here's the problem. If I were to do this then I'd have to create a file for every page I want to create that calls the script that pulls the content from the correct database row. So I could add all sorts of page names and contents into the table but I don't know how to call them without manually creating new files each time I want to link to a new page.
Ideally there'd be a script that creates links to pages based on the page name row of the DB table as the pages are created. But how do you get those links with the ?=pageName at the end? If I just knew how that worked then I could figure the rest out.
UPDATE
The second answer really confirmed everything I thought I had to do but there is one catch. My plan now is to split up all the code into a series of functions and either include or require them in different templates that will be used to format the way pages are displayed. I need one look for the home page and one other design for the rest of the pages. I'm thinking that I'll have a function that says if ID is 0 then call this page template.php else call this other template file.php. But how do I pass the required variables to these new files? Do I just include the index.PHP page in them?
Bill your actually on the right track. Almost all web software today does extensive URL processing. Traditionally you would have php pages on your web root and then utilize the query string in the URL to refine the page's output. You have already arrived at why this might not be desired. So the popular alternative is the Front Controller design pattern. Basically we funnel every request to your index.php page and then route the request to internal pages or apps outside the web root. This can get complicated fast and everybody seems to implement this pattern in unique ways.
We can utilize this pattern without the routing by simply putting our app in the index page. The script below shows an example of what your trying to do in the simplest of ways. We basically have one page with our script. We can request the virtual pages by changing the id query string in our url. For example www.demo.net/?id=0 can be utilized as an index to your site. This should be the same as www.demo.net without the 'id' query. Just keep solving those problems one by one even if you don't know what the problem is. Once you start looking at other peoples code, then you can start seeing how other people solved the same problems you have.
The solution below will get you started, but then what do you do when you want an admin page? How do you authenticate the user? Do you duplicate alot of the code for yet another page? If your serious about your CMS then your going to want to implement some kind of framework underneath it. A framework to process the url, route to your application, load configuration files, and probably manage your database connection. Yea it gets complicated, but not if you solve each problem one at a time. Utilize classes or functions to share code to start. At the very least include a common "bootstrap" file at the top of your page to initialize common functionality such as a database connection. Read Stack Overflow just to keep up with whats going on. You can learn alot of terminology and probably find some answers to questions you didn't even know you wanted to ask.
Below assume we have a table with the following fields:
page_id
page_name
page_title
page_body
<?php
//<--------Move outside of web root-------------->
define('DB_HOST', 'localhost');
define('DB_USER', 'cms');
define('DB_PASS', 'changeme');
define('DB_DB', 'cms');
define('DB_TABLE', 'cms_pages');
//<---------------------------------------------->
//Display errors for development testing
ini_set('display_errors','On');
//Get the requested page id
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
//Make page id '0' an index page to catch all
$id = 0;
}
//Establish a connection to MySQL
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
//Select the database we will be querying
mysql_select_db(DB_DB, $conn) or die(mysql_error());
//Lets just grab the whole table
$sql = "SELECT * FROM ".DB_TABLE;
$resultset = mysql_query($sql, $conn) or die(mysql_error());
//The Select Query succeeded, but returned 0 result.
if (mysql_num_rows($resultset)==0)
{
echo "<pre>Add some Pages to my CMS</pre>";
exit;
}
//This is our target array we need to fill with arrays of pages
$result = array();
//Convert result into an array of associative arrays
while($row = mysql_fetch_assoc($resultset))
{
$result[] = $row;
}
//We now have all the information needed to build our app
//Page name - Short name for buttons, etc.
$name = "";
//Page title - The page content title
$title = "";
//Page body - The content you have stored in a table
$body = "";
//Page navigation - Array of formatted links
$nav = array();
//Process all pages in one pass
foreach($result as $row)
{
//Logic to match the requested page id
if($row['page_id'] == $id)
{
//Requested Page
$name = $row['page_name'];
$title = $row['page_title'];
$body = $row['page_body'];
$page = "<b>$name</b>";
}
else
{
//Not the requested page
$page = $row['page_name'];
}
//Build the navigation array preformatted with list items
$url = "./?id=" . $row['page_id'];
$nav[] = "<li>$page</li>";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SimpleCMS | <?php echo $title; ?></title>
</head>
<body>
<div>
<div id="navigation" style="float:left;">
<ul>
<?php
foreach($nav as $item)
{
echo $item;
}
?>
</ul>
</div>
<div id="content"><?php echo $body;?></div>
</div>
</body>
</html>
I think you need to read about $_GET.
I also recommend a decent PHP book. Forget online tutorials; they are (for the most part) utterly useless.
I am developing a site using php and mysql. I want to know... what's a good way to deal with multi-lingual support? I want a user to be able to select from a drop down and select their language. Then everything (content, buttons, links) except the user-written content is in their language.
What's a good way to approach this? Use a cookie? Session?
Something like this works fine:
Langs.php
<?
// check if language switch as been set at url var
if ($_GET["lang_change"]) {
$_SESSION['session_name']["lang"] = $_GET["lang_change"];
}
// set value to lang for verification
$active_lang = $_SESSION['session_name']["lang"];
// verify $lang content and set proper file to be load
switch ($active_lang) {
case 'prt':
$lang_file = 'prt.php';
break;
case 'gbr':
$lang_file = 'gbr.php';
break;
case 'fra' :
$lang_file = 'fra.php';
break;
case 'esp' :
$lang_file = 'esp.php';
break;
case 'deu' :
$lang_file = 'deu.php';
break;
default:
$lang_file = 'gbr.php';
}
// load proper language file for site presentation
include_once ('$lang_file);
?>
LANG GBR FILE (gbr.php)
define("LANG_PAGETITLE_HOMEPAGE", 'Homepage');
define("LANG_BTN_KNOW_MORE", 'know more');
METHOD TO CHANGE LANGUAGE (url sample)
USE ENG
Basically, you have PHP files with constants, each file with a lang.
On click you set a url var (ex: lang_change = lang).
That will force page reload, and the langs.php file include at top of your index.php will load the selected language...
If you need more explanation about this, leave a comment and I'll send you a working sample!
Ps: session variables shown in this code is usefully for interaction with login systems, or just to avoid having the url parameters...
Save all dynamic content flagged with actual language
Make use of gettext() for buttons, etc. This one is much faster than including .php files with arrays
First of all you have to add all values in each language dynamically.
While adding dynamic content to your website, u can add languageId to each field of your tables in database. And then you can show that content at front end on behalf of that languageId.
I think it's a good idea to consider working with a framework that has internationalization support.
Take a look at this example using CakePHP http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial
I think the following will help you get some basic idea of developing it.
In a website, specially a multilingual website should have user interfaces / templates where hardcoded labels should be linked to variables. These variables should be loaded with correct language values. This can be done easily by including the language file containing the values in that specific language. You can have as many language files in a folder.
You will need to write a script in php, as whenever the user selects the language from the drop down, the page can reload with a language session. Another php script to fetch the selected language inside this session data and include the relevant language file inside the template/UI.
The same approach can be used in fetching content data from a table, where in all MySQL queries, you can use an additional lookup for language type from the content table. so that that file will be loaded.
SELECT * FROM posts WHERE lang='en' AND featured = 1
In many cases, the languages require HTML and CSS to be set accordingly to make the language render perfectly inside the browser. This means, you can also define language inside the HTML and in CSS define the fonts and directions (right to left or left to right).
I am recommending you to read the following in order to get more information on how to do it.
http://www.stylusinc.com/website/multilanguage_support.htm
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