My website has 2 languages. When I change language, I want the URL to change as well, similar to this:
www.domain.com
changing to this:
www.domain.com/th
and this:
www.domain.com/en
My php:
config.php
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
if(empty($_SESSION['language'])){
$_SESSION['language'] = "th";
}
if ($_SESSION['language'] == "th") {
include $_SERVER['DOCUMENT_ROOT'] . "/language/th.php";
} else {
include $_SERVER['DOCUMENT_ROOT'] . "/language/en.php";
}
$base_url = "/";
function lang($th, $en) {
if ($_SESSION['language'] == "th") {
return $th;
} else {
return $en;
}
}
lang.php
<?php
session_start();
switch ($_POST["lang"]) {
case "th":
$_SESSION['language'] = "th";
echo json_encode("complete");
break;
case "en":
$_SESSION['language'] = "en";
echo json_encode("complete");
break;
default :
break;
}
?>
links to change language
<li><a href="javascript:lang('th');" <?= $_SESSION['language'] == "th" ? 'class="active"' : ''; ?> >TH</a></li>
<li><a href="javascript:lang('en');" <?= $_SESSION['language'] == "en" ? 'class="active"' : ''; ?> >EN</a></li>
Can I use .htaccess to do this?
No, you can't acceess the PHP session from .htaccess. But you could use mod_rewrite to rewrite every request to your config.php.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# Only for non-existing directories, files or symlinks
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* config.php [L]
</IfModule>
Related
I want to write a project with regular files. The index file has a php code where all the files opened in the URL are switches. Like for example:
index.php
<?php
if(isset($_GET['page'])){
$current_page = isset($_GET['page']) ? $_GET['page'] : '';
}else{
$current_page = 'index';
}
$result = str_replace(".php","", $current_page);
switch($result){
case 'welcome':
include('sources/welcome.php');
break;
case 'index':
include('sources/index.php');
break;
case 'profile':
// Here is the problem. I want to make Facebook style user profile system
// But the switch can not see profile username because it is working just for page names not usernames
break;
}
?>
Like the code in the index.php file, I call the pages with the switch. But everything changes when the user opens the profile page. Because I want to make the profile pages of the members just like Facebook. Like http://www.mywebproject.com/username
My created htaccess is here:
.htaccess
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
RewriteRule (?:^|/)([\w-]+)/?$ profile.php?username=$1 [L,QSA]
My question is this. How can I call members' profiles with their username in switch.
How can I call members' profiles with their username in switch because there is no every username in $thePage array.
Just pass everything to the index.php
.htaccess:
# Activate rewrite engine
RewriteEngine on
RewriteBase /root/
# If the request is not for a valid directory, file or symlink
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
# Redirect all requests to index.php
RewriteRule ^(.*)$ index\.php?/$1 [QSA]
You just pass the $_REQUEST['username'] to the profile.php and then you render your page.
Something like:
index.php
// you can do this better, this is just an example:
$request_uri = $_SERVER['REQUEST_URI'];
$params_offset = strpos($request_uri, '?');
$request_path = '';
$request_params = [];
echo 'request_uri = ', $request_uri, '<br>', PHP_EOL;
if ($params_offset > -1) {
$request_path = substr($request_uri, 0, $params_offset);
$params = explode('&', substr($request_uri, $params_offset + 1));
foreach ($params as $value) {
$key_value = explode('=', $value);
$request_params[$key_value[0]] = $key_value[1];
}
} else {
$request_path = $request_uri;
}
echo 'request_path = ', $request_path, '<br>', PHP_EOL;
echo 'request_params = ', PHP_EOL; print_r($request_params);
if (preg_match('~/root/(photos|videos|albums)/([\w-]+)~', $request_uri, $match)) {
print_r($match);
unset($match);
require_once('photos_videos_albums.php');
} else if (preg_match('~/root/([\w-]+)~', $request_uri, $match)) {
$username = $match[1];
unset($match);
require_once('profile.php');
} else if ($request_path == '/root/') {
echo 'HOME';
exit();
} else {
header('HTTP/1.0 404 Not Found');
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
}
Excuse me , I just start to learn about .htaccess files . I'm trying to write it this way (my htaccess file)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /exmpl/vadik_route/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
ReqriteRule ^(.*)$ index.php/$l
</IfModule>
and my index.php
<?php
echo $_SERVER['PATH_INFO'];
?>
but server through this error.
Server error!
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
localhost
Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.15
How can I fix that
Change your .htaccess with this one:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
you can send the url by get method for example getme.php?url=/controller/model/
and you can take the url also divide by slash
$_GET['url'] //it is going to show you the url.
lets look at the .htaccess and explain it.
RewriteEngine On
RewriteBase / #dont forget to modify this part. it is explain which folder you project in
RewriteEngine On Options All -Indexes RewriteBase /directoryname/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
############### SEO ##########################
#http://www.example.com/hello/booboo/ it takes the url after .com/
RewriteRule ^(.*)$ getme.php?url=$1 [QSA,L]
now we sent all the url to getme.php and we can use it
getme.php
<?php
//we redirect to get in url=$1 so our get method name is url
$parca = explode("/", $_GET["url"]); //and we divided the url by slash .
echo $parca[0];//this is first part "/hello/
echo $parca[1];// and this is second part "/booboo/;
?>
<?php
session_start();
//Define Language file paths
define("LANG_EN_PATH", $_SERVER['DOCUMENT_ROOT'] . '/exmpl/sayt/multilang/en/');
define("LANG_RU_PATH", $_SERVER['DOCUMENT_ROOT'] . '/exmpl/sayt/multilang/ru/');
define("LANG_KR_PATH", $_SERVER['DOCUMENT_ROOT'] . '/exmpl/sayt/multilang/kr/');
define("LANG_TR_PATH", $_SERVER['DOCUMENT_ROOT'] . '/exmpl/sayt/multilang/tr/');
if (isset($_GET['lang']))
{
// GET request found
if ($_GET['lang'] == 'ru')
{
include LANG_RU_PATH . 'ru.php';
$_SESSION['lang'] = 'ru';
}
else if ($_GET['lang']=='en') {
include LANG_EN_PATH .'en.php';
$_SESSION['lang'] = 'en';
}
else if ($_GET['lang']=='tr') {
include LANG_TR_PATH .'tr.php';
$_SESSION['lang'] = 'tr';
}
else
{
include LANG_KR_PATH . 'kr.php';
$_SESSION['lang'] = 'kr';
}
}
//translate for russian
else if (isset($_SESSION['lang']))
{
if ($_SESSION['lang'] == 'ru')
{
include LANG_RU_PATH . 'ru.php';
}
//translate for kyrg
else if($_SESSION['lang'] == 'en')
{
include LANG_KR_PATH . 'en.php';
$_SESSION['lang'] = 'en';
}
// translate for turkish
if($_SESSION['lang'] == 'tr')
{
include LANG_TR_PATH . 'tr.php';
$_SESSION['lang'] = 'tr';
}
else {
include LANG_KR_PATH . 'kr.php';
}
}
else
{
include LANG_KR_PATH . 'kr.php';
$_SESSION['lang'] = 'kr';
}
?>
could you write path for this , as clear url
I have a problem with this url and I want to know how to rewrite that into htaccess. I'm pretty new into this stuff so I'm curious on how to do this, for example this url:
WEBSITE/?page=online
and rewrite it to, for example:
WEBSITE/page/online
or this url:
WEBSITE/?page=account&hide=x
to, for example:
WEBSITE/page/account/hide/x
I use this PHP script to include the pages inside one HTML document:
<?php
if (empty($_GET))
{
include 'pages/index.php';
} else {
if (!file_exists('pages/' . $_GET['page'] . '.php' ))
{
header("Location: /");
} else {
include 'pages/' . $_GET['page'] . '.php';
}
}
?>
In your .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Match SITE/page/account/hide/x, etc
RewriteRule ^/?page/([^\.*]+)/([^\.*]+)/([^\.*]+)?$ index.php?page=$1&$2=$3 [L,QSA]
# Match /SITE/page/online etc.
RewriteRule ^/?page/([^\.*]+)/?$ index.php?page=$1 [L,QSA]
You could do something like this.
.htaccess file
RewriteEngine On
RewriteRule (.*) control.php [L]
This says take every request coming to your server and sends it into the control.php file. Then in control.php we process all the gets to directories. You'll probably want some fallbacks, e.g. no GET request; should it go to the root, 404, 403?
control.php
<?php
$parts = '';
foreach($_GET as $key => $directories) {
$parts .= $key . '/' . $directories . '/';
}
header('Location: ' . '/' . $parts);
?>
In my webprojekt i use Routing + Clean URL's.
My htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
My index.php:
<?php
$projectname = "/FB-Clone2/";
$requestAction = substr($_SERVER['REQUEST_URI'], strlen($projectname), strlen($_SERVER['REQUEST_URI']));
$requestAction = explode("/", $requestAction);
$root = str_replace('\\', '/', dirname(__FILE__)).'/';
$GLOBALS['root'] = $root;
switch ($requestAction[0]) {
case 'login':
//require "$GLOBALS[root]/view/login.php";
header ("Location: $GLOBALS[root]/view/login.php");
break;
case 'register':
// require "$GLOBALS[root]/view/register.php";
header ("Location: $GLOBALS[root]/view/register.php");
break;
default:
//require "$GLOBALS[root]/view/login.php";
header ("Location: $GLOBALS[root]/view/login.php");
break;
}
return;
?>
In the index.php in the switch-case-construct there are in each case commented out a require line and da header() line.
My problem:
If u use in all thre cases the requiere line then all works perfect.
But if i use the index.php as shown above (with header() instead of requiere) then nothing works. I get no error and the site is not even loaded...
Where is the problem?
I'm trying to achieve clean URLs on my localhost (so when I write localhost/contact, it redirects me to localhost/contact.php), but it's not working. I did it according to the older tutorial I found on YouTube, but I probably didn't understand well some parts. Many thanks for every answer. Here is my code:
.htaccess // I am sure I have mod_rewrite allowed.
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
</IfModule>
Script in index.php
include_once('classes/simpleUrl.php');
$url = new simpleUrl('localhost');
$test = $url->segment(1);
if (!$url->segment(1)) {
$page = 'home';
}
else {
$page = $url->segment(1);
}
switch ($page) {
case 'home' :
echo 'Home page';
break;
case 'contact':
echo 'Contacts page';
break;
default:
echo '404';
break;
}
classes/simpleUrl.php
class simpleUrl {
var $site_path;
function __toString() {
return $this->site_path;
}
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
function __construct($site_path) {
$this->site_path = $this->removeSlash($site_path);
}
function segment($segment) {
$url = str_replace($this->site_path, '', $_SERVER['REQUEST_URI']);
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
$url = new simpleUrl('localhost');
localhost is not shown in $_SERVER['REQUEST_URI'] so in this case you may simply use $url = new simpleUrl('index.php');
OR
Use this code for .htaccess :
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [L]
because when you do this:
RewriteRule ^(.*)$ index.php/$1
Your actual URL may become something like this:
localhost/index.php/contact
So it's better requested URL to stay same.
but in this case use:
$url = new simpleUrl('');
Oho, look at this mistery:
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
when passed $string does not ends with slash it returns nothing, so have to change it in such:
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
}
return $string;
}
Now I'll explain when and why to use $site_path for simpleUrl constructor:
if you have running your script in subdirectory, for ex: if you are working under /www/test/ then you should you test as param to pass to simpleUrl constructor, otherwise leave it blank
Update 3
You should change simpleUrls segment method to this:
function segment($segment) {
$url = trim(str_replace($this->site_path, '', $_SERVER['REQUEST_URI']),'/');
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
and next use 0 as index instead of 1 - $url->segment(0)
I'm not sure if you wish to use more variables like: www.domain.com/folder-with-website/products/product-name or if you could live with: www.domain.com/folder-with-website/products?id=123
But try this:
index.php
<?php
$page = $_GET["page"];
if(file_exists("pages/{$page}.php")) {
include("pages/{$page}.php");
} else if(empty($page)) {
include("pages/home.php");
} else {
echo "This page does not exists";
}
?>
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1
Options -Indexes
Link setup
<ul>
<li>
Home <!-- Just a page without any variables -->
</li><li>
Products <!-- same as Home -->
</li><li>
Details about product <!-- Page with a variable / extra information -->
</li><li>
Details about product <!-- Page with more variables -->
</li>
</ul>