.htaccess Handle uri with php - php

I have a codebase that uses the logic,
if($_SERVER['HTTP_HOST'] == 'fr.example.com')
{
$_SESSION["lang"] = "fr";
}
elseif($_SERVER['HTTP_HOST'] == 'en.example.com')
{
$_SESSION["lang"] = "en";
}
I want:
www.example.com should serve english
www.example.com/fr should serve french.
All the text is served from the database.
How can I use same index.php to serve english and french content based on what language is there in the URI?

Since you want to handle this in PHP anyway, there is no need for an .htaccess file. Just use $_SERVER['REQUEST_URI'], e.g.
$uri = $_SERVER['REQUEST_URI'];
if (stripos($uri, "/fr/") === 0) {
// handle french
} elseif (stripos($uri, "/de/") === 0) {
// handle german
} else {
// handle english
}

Related

Cannot redirect correctly with PHP

I have a blog in a website that I want to redirect.
For example this URL https://example.com/blog/june-2021/name-of-blog-post should redirect to https://example2.com/blog/june-2021/name-of-blog-post
There are hundreds of blog posts so I can't use an array to redirect them one by one.
I'm using Pantheon as the host. I added the script to settings.php.
Currently everything from example.com goes to example2.com, so it's not working correctly.
Here's my script:
$url = $_SERVER['REQUEST_URI'];
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
$blog = $uri_segments[0];
$post_date = $uri_segments[1];
$post_name = $uri_segments[2];
if ((stripos($url, "/blog/") === 0) && (php_sapi_name() != "cli")) {
header('HTTP/1.0 301 Moved Permanently'); header("Location: https://example2.com".$blog.$post_date.$post_name);
if (extension_loaded('newrelic')) {
newrelic_name_transaction("redirect");
}
exit(); }
Thanks in advance!
You can check for /blog/ by checking that it is found !== false anywhere in $_SERVER['REQUEST_URI']:
if ((stripos($url, "/blog/") !== false) && (php_sapi_name() != "cli")) {
Or check to see if it is found at the first 0 position of $_SERVER['REQUEST_URI']:
if ((stripos($url, "/blog/") === 0) && (php_sapi_name() != "cli")) {
Notes:
stripos only takes three arguments and you only need the first two.
Location header should consist of a single absolute URI like https://example2.com/blog/june-2021/name-of-blog-post, so you might look at the other $_SERVER variables to construct one.

Changing the path in a URL for a multilingual website

I am coming to you to find out if it is possible to change the path in a URL using a PHP variable.
My goal would be to organize my website with 2 folders (one for each language), choose the language on a random page in one of the two folders and be able to change the language by modifying the URL.
For example, I'm on http://truc.com/fr/test.php; I change the language and I get http://truc.com/en/test.php.
I've done a test that works but I'd prefer something more dynamic, that will work on all the pages of the website:
fichier index.php
<?php
session_start();
if (!isset($_SESSION['lang']))
if (!isset($_SESSION['lang']))
$_SESSION['lang'] = "fr";
else if (isset($_GET['lang']) && $_SESSION['lang'] != $_GET['lang'] && !empty($_GET['lang']))
{
if ($_GET['lang'] == "fr")
$_SESSION['lang'] = "fr";
else if ($_GET['lang'] == "en")
$_SESSION['lang'] = "en";
}
if($_SESSION['lang']==fr)
{
header('Location: http://localhost/site/languages/fr/index.php');
}
else if($_SESSION['lang']==en)
{
header('Location: http://localhost/site/languages/en/index.php');
}
?>
Adjusted your code and added a new variable $page_language that handles the page language and redirects to specific link for various languages and before redirecting to the page a session language is set to remember it on next page . Good luck
if (isset($_SESSION['lang'])) {
$page_language = $_SESSION['lang'];
} elseif (isset($_GET['lang']) && !empty($_GET['lang'])) {
$page_language = $_GET['lang'] ;
} else {
$page_language = "fr" ; //set default language if no session and url has language
}
if ($page_language == "fr") {
$_SESSION['lang'] = "fr"; //set session language for later visits
header('Location: http://localhost/site/languages/fr/index.php');
exit;
} elseif ($page_language == "en") {
$_SESSION['lang'] = "en"; //set session language for later visits
header('Location: http://localhost/site/languages/fr/index.php');
exit;
}

Rewriting URL's from a PHP Redirection

How can i rewrite this url:
http://localhost/?=register
To look like this?:
http://localhost/index.php/Register
Your redirection code:
header('Location: /index.php/Register/',true,302);
exit;
For accessing the /Register/ value, use:
$_SERVER['PATH_INFO']
After performing the redirection using the header command, you must remember to write your code to process that URL.
/index.php/Register will try to load a "Register" file inside "/index.php/" folder ... 404 error
So you will need to use apache modrewrite to redirect these "virtual folders" to a centralized script that can handle it.
Something like this on .htaccess:
RewriteEngine on
RewriteRule ^index.php/(.*)$ index.php
Then, at your index.php, you will treat the incomming URL to detect that file, and do whatever you want with it.
I usually work with a catch-all (redirects everything to /index.php) and then break the URL and treat it, so I can have any number of virtual folder/files. Here is my own function to treat any incoming request:
function extractUri($uri="") {
if ($uri == "") $uri = isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != "" ? $_SERVER['REQUEST_URI'] : "";
if ($uri != "") {
# removes query from request
if ($uri[0] != "/") $uri = "/".$uri; # ALWAYS START WITH /
$uri = explode("?",$uri);
$uri = str_replace("..",".",array_shift($uri)); # little exploit remover
$uri = explode("/",str_replace("//","/",$uri));
} else
$uri = array("/");
$context = array();
foreach ($uri as $part)
array_push($context,preg_replace("/(\.){2,}/","\.",$part)); # prevents ..
$action = array_pop($context); # file (with extension)
$original_action = $action; # preserve the original file with extension (I work w/o them)
$ext = "";
if ($action == "") $action = 'index'; # so if you are accessing folder/, then you probably want the index
else if (strpos($action,".")!==false) { # remove extension
$action = explode(".",$action);
$ext = array_pop($action);
$action = implode(".",$action);
$action = removeSimbols($action,true,false); # makes sure it is a valid filename, this function removes any weird character
}
return array($context,$action,$original_action,$ext); # returns the folder structure (array), the page/action, the page/action with extension, and said extension (lots of repetition to speed up later)
}
so extractUri("/index.php/Register") would return:
Array ([0] => "/", [1] => "index.php"), "Register", "Register", ""

http redirect loop ,multilangual website

I'm trying to make my site in two language, in English (en) and in Azerbaijani (az)
I store the language in the $_SESSION variable, the default language is English and I keep the language files in web root and Azerbaijani in an az folder.
My problem is when the language is changed for example to az I redirect the user to http://thephotofilm/az/...... and I dont want the users go to http://thephotofilm.com/...... because the current language is az so I tried some ways but sometimes I have redirect loops and I can't figure it out
$request_uri = $_SERVER['REQUEST_URI'];
if( isset($_SESSION['lang']) ) {
$lang=$_SESSION['lang'];
}
if( isset($_COOKIE['lang']) ) {
$lang=$_COOKIE['lang'];
}
if( $lang == "az" && strpos($request_uri,"/az/", 0) !== 0 ) {
header("Location: /az".$request_uri);
}
if( $lang=="en" && strpos($request_uri,"/az/", 0) === 0 ) {
header("Location: ".substr($request_uri, 3));
}
You can just set the path in a variable for selected version.
For eg:
if(english)
$base_url="http://thephotofilm.com/" // for English
else
$base_url="http://thephotofilm.com/az" // for Azerbaijani
Then start each link with variable $base_url

Detect URL that app is being accessed from

I am currently developing a PHP application that is (hopefully) going into production use soon.
What I'm needing help with is detecting what URL the app is being accessed on ie dev.local, testing.domain.com or app.domain.com and then using the correct MySQL DB, ie app_test for dev and testing and app_prod for the production server.
Along with that, I also want to be able to modify the internal URLs to match (several emails are sent that also need to be tested with the correct URL).
I remember seeing some stuff about it before but am not able to find it any more.
Get full url of page
function request_url() {
$result = '';
$default_port = 80;
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']=='on')) {
$result .= 'https://';
$default_port = 443;
} else {
$result .= 'http://';
}
$result .= $_SERVER['SERVER_NAME'];
if ($_SERVER['SERVER_PORT'] != $default_port) {
$result .= ':'.$_SERVER['SERVER_PORT'];
}
$result .= $_SERVER['REQUEST_URI'];
return $result;
}
I think you will be enough: $_SERVER['SERVER_NAME']
Easy way to do that ......
Define environment constants in constants.php file
// constants.php
define('ENVIRONMENT', 'development');
//define('ENVIRONMENT', 'production'); // uncomment this when your going to live your project
define general functions in general.php
// general.php
include "constants.php";
function is_production()
{
if(ENVIRONMENT == "production")
{
return TRUE;
}
return FALSE;
}
function is_development()
{
if(ENVIRONMENT == "development")
{
return TRUE;
}
return FALSE;
}
Now you can us that functions in your database connection files and select your database and base url
// in db.php
include "general.php";
if(is_production())
{
$conn = mysql_connect("host1","username1","password1");
mysql_select_db("db1",$conn);
define('BASE_URL', 'http://domain.com');
}
else if(is_development())
{
$conn = mysql_connect("host2","username2","password2");
mysql_select_db("db1",$conn);
define('BASE_URL', 'http://testing.domain.com');
}
Now You can use that BASE_URL constant and you have database connection as you want
This general overview but you can implement in your project as your standered.. :)

Categories