Rewrite rules in the .htaccess file - mod-rewrite

The request is simple, however, I cannot find a way to implement it. I have links like:
httр://mysite.com/index.php?lang=EN
httр://mysite.com/index.php?route=add&lang=EN
httр://mysite.com/index.php?route=view&lang=EN
and so on. What I want is to create 301 redirects so that EN could be changed to GB. For example, if a customer opens httр://mysite.com/index.php?route=add&lang=EN, he should be redirected to httр://mysite.com/index.php?route=add&lang=GB.
I have searched for this for days and have failed to find a working solution. Please help.

Does it have to be done in .htaccess? Here's a relatively simple way of doing it in PHP:
<?
if ("EN" == $_GET['lang']) {
$params = $_GET;
$params['lang'] = "GB";
$query_strings = array();
foreach ($params as $key => $value) {
$query_strings[] = $key . "=" . $value;
}
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.mysite.com?" . join($query_strings, "&");
}
Bottom line is that it may be easier to fix this problem on a level where you can isolate each query parameter and look at just the lang parameter and determine whether to do a redirect.
With regular expressions (as you would need to use in .htaccess) it's harder to isolate just the lang part. You would also need one line per language you want to redirect and maintain the list.

Related

Laravel 8 multilanguage routes and how get the translated link of the same page

I'm trying to make my test app in multilanguage way.
This question has two correlated questions:
First question:
I followed the second answer in How to create multilingual translated routes in Laravel and this help me having a multilanguage site and the route cached, but I've a question and some misunderstanding.
It's a good practice overwrite an app config as they do int the AppServiceProver.php, making:
Config::set('app.locale_prefix', Request::segment(1));
Isn't better to work with the Session::locale in any case?
Second question:
In my case I've two languages, and in the navbar I want to print just ENG when locale is original language, and ITA when session locale is English.
If I'm in the Italian page, the ENG link in the navbar should point to the same English translated page.
Working with the method used in the other question, I hade many problems caused by the:
Config::set('app.locale_prefix', Request::segment(1));
We overwrite the variable in the config file local_prefix, and every time I switch to English language the locale_prefix will change to 'eng' and this sounds me strange, another thing I did is this:
if ( $lang && in_array($lang, config('app.alt_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
We use the alt_langs where are defined only the alternative languages, and this is a problem cause if I pass the local lang, in my case 'it', like lang parameter, this will not be found cause, from the description, the alt_lang should not contain the locale language and you will be able to get only the translated string.
If I change the:
if ( $lang && in_array($lang, config('app.alt_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
in:
if ( $lang && in_array($lang, config('app.all_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
Now using app.all_langs I'm able to choose which URL you want and in which language I want.
How do I get the translated URL?
In the blade file I need to get the translated URL of the page, and if read the other question, we used the $prefix for caching the routes and giving to the route a new name ->name($prefix.'_home'); in this way I can cache all the route and I can call the routes using blade without prefix {{ route('name') }} but, needing the translated url of the actual page a made this on the top of the view:
#php
$ThisRoute = Route::currentRouteName();
$result = substr($ThisRoute, 0, 2);
if ($result =='it' ){
$routeName = str_replace('it_', '', $ThisRoute);
$url = route($routeName,[],true,'en');
} else {
$routeName = str_replace('en_', '', $ThisRoute);
$url = route($routeName,[],true,'it');
}
#endphp
Doing this I get the actual route name that should be it_home I check if start with it_ or en_, I remove the it_ or en_ prefix and I get the translated URL, now you can use the $url as <a href="{{ $url" }}>text</a> cause if I call the {{ route('page') }} I get the link, with the locale language.
This code is not very good, I know, but I written in 5 minutes, need more implementation, and check, but for the moment is just to play with Laravel.
It's a good way?? How can I do it better (except the blade link retrieving)?? Many solution I found used middleware, but I would like to avoid a link in the navbar like mysite.com/changelang?lang=en
Is a good approach overriding the app.locale_prefix?
First
according to your question, it's a bad practice to save the preferences into .env or session because as soon as the session is finished the saved language will be removed also it's common when you need to store any preferences related to your website such as (Color, Font, Language, ...etc) you must store any of them into the cache.
Second
honestly, your code is a very strange and NOT common way and there are two ways to handle what do you need
First
There is a very helpful and awesome package called mcamara it'll help you too much (I recommend this solution).
Second
you can do it from scratch using the lang folder located in the resource folder and you must create files with the same count of the needed languages then use the keys that you'll define into these files into views and you can prefix your routes with the selected language you can use group method like so
Route::group(['prefix' => 'selected_lang'], function() {
Route::get('first_route', [Controller::class, 'your_method']);
});
or you can add the selected language as a query string like so localhost:8000/your_route?lang=en you can follow this tutorial for more info.

Get segment from url CodeIgniter but not first

I know i can get all segments from url like this
Lets say i have this example link
www.example.com/de/products.html
Using url_helper like this:
$data['url'] = $this->uri->uri_string();
I will get value like this
de/products
But i dont need first segment de, only products, the problem is that
i dont know how many segments it will be, i only need to remove the first
Is there possible to forget first segment with url helper in CI?
Try like this...
Use the php's explode() function to make the url string as array.Then apply array's array_shift() function which always removes the first element from array.
Code is looks like as below
$data= $this->uri->uri_string();
$arr=explode('/', $data);
array_shift($arr);
//print_r($arr);
Then use the php's implode() method to get the URI without first segment.Hope it will works...
$uri=implode('/',$arr);
echo $uri;
There is no URL helper in the CI to forget the first segment. However you can easily make a custom one and put #Hikmat's answer below it in the application/helpers/MY_url_helper.php in the Core folder.
e.g.
function my_forget_first_segment() {
$data= $this->uri->uri_string();
$arr=explode('/', $data);
array_shift($arr);
$uri=implode('/',$arr);
return $uri;
}
Before Edit answer.
You need to try this
$second_segment = $this->uri->segment(2);
From Codeigniter documentation -
$this->uri->segment(n);
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this:
http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news
2. local
3. metro
4. crime_is_up
The optional second parameter defaults to NULL and allows you to set the return value of this method when the requested URI segment is missing. For example, this would tell the method to return the number zero in the event of failure:
$product_id = $this->uri->segment(3, 0);
example:
<?php
$data=$this->uri->segment(2);
$val=explode('.', $data);
echo $val[0];
?>

Search specific text with DOM XPath

I have been trying to crawl a website pages and search for specific text using simple html dom and XPath. I have get all the links from website and trying to crawl that links and search text on all pages. The text that i want to search is within html span tag.
But no output is shown.
whats going wrong ?
here is my code
<?php
include_once("simple_html_dom.php");
set_time_limit(0);
$path='http://www.barringtonsports.com';
$html = file_get_contents($path);
$dom = new DOMDocument();
#$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for($i = 0; $i < $hrefs->length; $i++ ){
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
$nurl = $path.$url;
$html1 = file_get_contents($nurl);
$dom1 = new DOMDocument();
#$dom1->loadHTML($html1);
$xpath1 = new DOMXPath($dom1);
$name = $xpath1->evaluate("//span[contains(.,'Asics Gel Netburner 15 Netball Shoes')]");
if($name)
echo"text found";
}
?>
I just want to check the whether text "Asics Gel Netburner 15 Netball Shoes" exist in any page of the website www.barringtonsports.com or not.
You're querying a lot of web-pages interactively. It takes more time than your server is allowed to use for generating pages.
You can execute this script from command-line to avoid timeouts or you can try to configure PHP and WebServer so they give more time to the script (you can ask on https://serverfault.com/ how to do this)
Well, first off you are mixing Simple HTML DOM and DOM Document. Just use one or the other. Since this is in the simple-html-dom tag start with this from the command line:
<?php
require_once("./simple_html_dom.php"); # simplehtmldom.sourceforge.net to use manual
$path="http://www.barringtonsports.com";
$html = file_get_html($path);
foreach ($html->find('a') as $anchor) {
$url = $anchor->href;
echo "Found link to " . $url . "\n";
# now see if the link is relative, absolute, or even on another site...
$checkhtml = file_get_html($url);
# now you can parse that link for stuff too.
}
?>
But really, that website has a search form, why not just send it a query instead and read the results?

Append variables to URL after pagination's '/page/x'

I'm using a couple URI variables to handle sorting a table, like this
.../page/7/sortby/serial_number/orderby/desc
as you can see, I'm also using the built in CI pagination library. My problem right now is that the links created with $this->pagination->create_links(); strip off sorting variables from the URI, making it difficult to maintain these sorting options between pages.
How can I go about appending these variables sortby/foo/orderby/bar to the URI of links created by the pagination library?
You can use the base_url option, and the page number segments will have to be last. It's a little annoying, but I think it's the simplest way.
// Get the current url segments
$segments = $this->uri->uri_to_assoc();
// Unset the "page" segment so it's not there twice
$segments['page'] = null;
// Put the uri back together
$uri = $this->uri->assoc_to_uri($segmenmts);
$config['base_url'] = 'controller/method/'.$uri.'/page/';
// other config here
$this->pagination->initialize($config);
I found the answers thanks to WesleyMurch leading me in the right direction. In order to always have the page variable as the last in the uri (which is necessary when using CI's pagination library), I used this
$totalseg = $this->uri->total_segments();
$config['uri_segment'] = $totalseg;
then following WesleyMurch's idea, I rebuilt the base_url,
$segments = $this->uri->uri_to_assoc();
unset($segments['page']); //so page doesn't show up twice
$uri = $this->uri->assoc_to_uri($segments);
$config['base_url'] = site_url()."/controller/method/".$uri."/page/";
and of course initialize the pagination with all the correct config options
$this->pagination->initialize($config);
I use the answer of ejfrancis but...
If for some reason the user put not numeric or negative number in the url's page var, i suggest make a validation before set the $config['uri_segment'], like this one:
$totalseg = $this->uri->segment($totalseg)>0 &&
is_numeric($this->uri->segment($totalseg))?
$totalseg : NULL;
I hope it help!

How do I get the suffix (in code) that is being used for urls?

Magento can add a suffix that is defined by the user to append onto urls. I want to get that suffix from my code. Does anyone know an easy way to do this?
If it's stored in the configuration area, then you access it just as you would any other configuration value, by using Mage::getStoreConfig($config_path) where $config_path is defined in the system.xml of the module that defines it.
If you're not sure of the $config_path, then I usually cheat and inspect the textbox/dropdown in the configuration section, take a look at the id, e.g. dev_log_file, and translate it to dev/log/file. You'll need to use some intelligence when there are multiple _ though :)
Nick's answer is good but the actual answer to this question is:
$suffix = Mage::helper('catalog/category')->getCategoryUrlSuffix();
If I am not mistaken, here is the code ( because I don't understand what you want with URL )
<?php
$currentUrl = $this->helper('core/url')->getCurrentUrl();
$url_parts = split('[/.-]', $currentUrl); // escape characters should change based your url
echo $url_parts[0]; //check here
?>
complete product url:
$productId = ***;
$productUrl = Mage::getBaseUrl().Mage::getResourceSingleton('catalog/product')->getAttributeRawValue($productId, 'url_key', Mage::app()->getStore()).Mage::helper('catalog/product')->getProductUrlSuffix();

Resources