Change Language without leaving current page - php

I am trying to change languages but stay on the current page:
i.e:
www.myurl.com/english/aboutus.php
www.myurl.com/german/aboutus.php
www.myurl.com/french/aboutus.php
So only the language directory changes.
I have the following but can't get it to work:
<?php
$full_url = $_SERVER['FULL_URL'] ;
$temparray = explode(".com/",$full_url,2);
$englishtemp = $temparray[0] . ".com/english/" . $temparray[1];
$englishlink = "<a href=$englishtemp><img src=../images/english-flag.jpg></a>";
echo $englishlink;
?>
I get the url to change from '/french/aboutus.php' to '/english' but it doesn't remember the page name 'aboutus.php' and returns to the index page.
Could any one please help?

Use basename($_SERVER['PHP_SELF']) for the current page.
$englishtemp = "/english/" . basename($_SERVER['PHP_SELF']);
$englishlink = "<a href=$englishtemp><img src=../images/english-flag.jpg></a>";
echo $englishlink;
See PHP documentation on $_SERVER.

Try this instead. It will generate links for all the languages except the current selected one :)
<?php
$full_url = $_SERVER['REQUEST_URI']; //select full url without the domain name
$languages = array('english', 'french', 'german'); //array of all supported languages
$url_bits = explode('/', $full_url); //divide url into bits by /
$current_language = $url_bits[1]; //current language is held in the second item of the array
//find current language in the array and remove it so we wouldn't have to display it
unset($languages[array_search($current_language, $languages)]);
$links = '';
foreach ($languages as $language) {
//generate links with images for the rest of the languages
$links .= '<img src="../images/' . $language . '-flag.jpg" title="'.ucfirst($language).'" />';
}
echo $links;
?>

Related

How To Output User Submitted Links On Your Webpage Securely?

I want to allow my website visitors (any Tom, Dick & Harry) submit their links to my webpage for output on my page.
I need to parse user submitted urls before echoing their submitted urls on my page. Need to parse the urls as I won't know what urls they will be submitting nor the structures of their urls.
A user could theoretically visit my page and inject some Javascript code using, for example:
?search=<script>alert('hacked')</script>
You understand my point.
I got to write php script that when users submit their urls, then my php script parses their urls and encodes them by adding urlencode, rawurlencode, intval in the appropriate places before outputting them via htmlspecialchars.
Another wrote this following script. Problem is, it outputs like so:
http%3A%2F%2Fexample.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13
It should output like this:
http://example.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=13
This is their code ....
Third Party Code:
<?php
function encodedUrl($url){
$query_strings_array = [];
$query_string_parts = [];
// parse URL & get query
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query_strings = parse_url($url, PHP_URL_QUERY);
// parse query into array
parse_str($query_strings, $query_strings_array);
// separate keys & values
$query_strings_keys = array_keys($query_strings_array);
$query_strings_values = array_values($query_strings_array);
// loop query
for($i = 0; $i < count($query_strings_array); $i++){
$k = urlencode($query_strings_keys[$i]);
$v = $query_strings_values[$i];
$val = is_numeric($v) ? intval($v) : urlencode($v);
$query_string_parts[] = "{$k}={$val}";
}
// re-assemble URL
$encodedHostPath = rawurlencode("{$scheme}://{$host}{$path}");
return $encodedHostPath . '?' . implode('&', $query_string_parts);
}
$url1 = 'http://example.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=13';
$url2 = 'http://example.com/autos/cars/list.php?state=california&max_price=50000';
// run urls thru function & echo
// run urls thru function & echo
echo $encoded_url1 = encodedUrl($url1); echo '<br>';
echo $encoded_url2 = encodedUrl($url2); echo '<br>';
?>
So, I changed this of their's:
$encodedHostPath = rawurlencode("{$scheme}://{$host}{$path}");
to this of mine (my amendment):
$encodedHostPath = rawurlencode("{$scheme}").'://'.rawurlencode("{$host}").$path;
And it seems to be working. As it's outputting:
http://example.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=13
QUESTION 1:
But I am not sure if I put the raw_urlencode() in the right places or not and so best you check.
Also, should not the $path be inside raw_urlencode like so ?
raw_urlencode($path)
Note however that:
raw_urlencode($path)
doesn't output right.
QUESTION 2:
I FURTHER updated their code to a new VERSION and it's not outputting right. Why is that ? Where am I going wrong ?
All I did was add a few lines.
This is my update (NEW VERSION) which outputs wrong. Outputs like this:
http%3A%2F%2Fexample.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13
I added a few lines of my own at the bottom of their code.
MY UPDATE (NEW VERSION):
<?php
function encodedUrledited($url){
$query_strings_array = [];
$query_string_parts = [];
// parse URL & get query
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query_strings = parse_url($url, PHP_URL_QUERY);
// parse query into array
parse_str($query_strings, $query_strings_array);
// separate keys & values
$query_strings_keys = array_keys($query_strings_array);
$query_strings_values = array_values($query_strings_array);
// loop query
for($i = 0; $i < count($query_strings_array); $i++){
$k = urlencode($query_strings_keys[$i]);
$v = $query_strings_values[$i];
$val = is_numeric($v) ? intval($v) : urlencode($v);
$query_string_parts[] = "{$k}={$val}";
}
// re-assemble URL
$encodedHostPath = rawurlencode("{$scheme}").'://'.rawurlencode("{$host}").$path;
return $encodedHostPath . '?' .implode('&', $query_string_parts);
}
if(!ISSET($_POST['url1']) && empty($_POST['url1']) && !ISSET($_POST['url2']) && empty($_POST['url2']))
{
//Default Values for Substituting empty User Inputs.
$url1 = 'http://example.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=138';
$url2 = 'http://example.com/autos/cars/list.php?state=california&max_price=500008';
}
else
{
//User has made following inputs...
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
//Encode User's Url inputs. (Add rawurlencode(), urlencode() and intval() in user's submitted url where appropriate).
$encoded_url1 = encodedUrledited($url1);
$encoded_url2 = encodedUrledited($url2);
}
echo $link1 = '<a href=' .htmlspecialchars($encoded_url1) .'>' .htmlspecialchars($encoded_url1) .'</a>';
echo '<br/>';
echo $link2 = '<a href=' .htmlspecialchars($encoded_url2) .'>' .htmlspecialchars($encoded_url2) . '</a>';
echo '<br>';
?>
This thread is really about the 2nd code. My update.
Thank You!
I fixed my code.
Answering my own question.
Fixed Code:
function encodedUrledited($url){
$query_strings_array = [];
$query_string_parts = [];
// parse URL & get query
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query_strings = parse_url($url, PHP_URL_QUERY);
// parse query into array
parse_str($query_strings, $query_strings_array);
// separate keys & values
$query_strings_keys = array_keys($query_strings_array);
$query_strings_values = array_values($query_strings_array);
// loop query
for($i = 0; $i < count($query_strings_array); $i++){
$k = $query_strings_keys[$i];
$key = is_numeric($k) ? intval($k) : urlencode($k);
$v = $query_strings_values[$i];
$val = is_numeric($v) ? intval($v) : urlencode($v);
$query_string_parts[] = "{$key}={$val}";
}
// re-assemble URL
$encodedHostPath = rawurlencode($scheme).'://'.rawurlencode($host).$path;
$encodedHostPath .= '?' .implode('&', $query_string_parts);
return $encodedHostPath;
}
if(!ISSET($_POST['url1']) && empty($_POST['url1']) && !ISSET($_POST['url2']) && empty($_POST['url2']))
{
//Default Values for Substituting empty User Inputs.
$url1 = 'http://example.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=138';
$url2 = 'http://example.com/autos/cars/list.php?state=california&max_price=500008';
}
else
{
//User has made following inputs...
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
//Encode User's Url inputs. (Add rawurlencode(), urlencode() and intval() in user's submitted url where appropriate).
}
$encoded_url1 = encodedUrledited($url1);
$encoded_url2 = encodedUrledited($url2);
$link1 = '<a href=' .htmlspecialchars($encoded_url1) .'>' .htmlspecialchars($encoded_url1) .'</a>';
$link2 = '<a href=' .htmlspecialchars($encoded_url2) .'>' .htmlspecialchars($encoded_url2) . '</a>';
echo $link1; echo '<br/>';
echo $link2; echo '<br/>';
?>
These 2 following lines were supposed to be outside the ELSE. They weren't. Hence all the issue. Moved them outside the ELSE and now script working fine.
$encoded_url1 = encodedUrledited($url1);
$encoded_url2 = encodedUrledited($url2);

Unable to print links in another function

I've written some code in php to scrape some preferable links out of the main page of wikipedia. When I execute my script, the links are coming through accordingly.
However, at this point I've defined two functions within my script in order to learn how to pass links from one function to another. Now, my goal is to print the links in the latter function but it only prints the first link and nothing else.
If I use only this function fetch_wiki_links(), I can get several links but when i try to print the same within get_links_in_ano_func() then it prints the first link only.
How can I get them all even when I use the second function?
This is what I've written so far:
include("simple_html_dom.php");
$prefix = "https://en.wikipedia.org";
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links = $prefix . $links;
return $absolute_links;
}
}
function get_links_in_ano_func($absolute_links)
{
echo $absolute_links;
}
$items = fetch_wiki_links($prefix);
get_links_in_ano_func($items);
Your function returned the value at the very first iteration. You will need something like this:
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
$absolute_links = array();
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links []= $prefix . $links;
}
return implode("\n", $absolute_links);
}

Change Attribute Some Links on Content

I'm building plugin wordpress for change attribute some links on content of post. I have function like this :
public static function encrypt_link_content( $content ){
if ( strpos( $content, 'safelinkThis' ) !== false ) {
// get dom from string of content
$content = str_get_dom($content);
// find link with attribute data-role=safelinkThis
$all_links = $content('a[data-role=safelinkThis]');
$count_links = count($all_links);
$i = 0;
$_links = self::get_links_post($count_links);
foreach ($all_links as $a) {
$href = $a->href;
$encrypt = self::zi_encrypt($href);
$a->href = $_links[$i]."?link=".$encrypt;
$i += 1;
}
$content = (string) $content;
}
return $content;
}
That function is work, Attribute href of link have been changed.
example of content :
Find us on :
Go to facebook
Go to google
Go to Twitter
Will be change to like this :
Find us on :
Go to facebook
Go to google
Go to Twitter
I'm use http://code.google.com/p/ganon/ library to find dom in string.
Now
I have a custom table for store domain exception, The name is wp_sf_domain. I won't change a link if it have href attribute with domain exception from wp_sf_domain.
I know, I can use this
global $wpdb;
$sf_table_name = $wpdb->prefix . 'sf_domain';
foreach ($all_links as $a) {
$href = $a->href;
$aDomain = parse_url($href)['host'];
$record = $wpdb->get_results( "SELECT * FROM $sf_table_name WHERE domain='$aDomain'" );
if(count($record) == 0){
// change this link
}
}
But I think this is a bad practice if I have many links on content, I should check one by one to database.
How can I compare between host of link on content with list domain in database and change a link attribute href if host of link not include in database?

PHP - remove last part from URL

Good day to all!
I need to grab article's URL and modify it by deleting the last part of it (moving one level up).
Grabbing the current URL with Wordpress function <?php echo get_permalink( $post->ID ); ?>
Example of use. My current article's URL:
http://example.com/apples/dogs/coffee
Delete the last part of URL so it will be:
http://example.com/apples/dogs
(And with no slash at the end)
So this will return the current Wordpress URL:
Text
but how can I delete the last part of it?
Thanks in advance!
$url = 'http://example.com/apples/dogs/coffee';
$newurl = dirname($url);
Most of the answers written here would work, but it's a bad practice to parse a url using explode and RegExp. It's better to use the PHP function parse_url. In this case, you can't encounter a problem if the url changes. This code will omit the last part of the url's fragment.
Here's the code:
<?php
$url = 'http://example.com/apples/dogs/coffee';
$parsed_url = parse_url($url);
$fragment = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] : '';
$new_fragment = '';
if(!empty($fragment)){
$fragment_parts = explode('/', $fragment);
// Remove the last item
array_pop($fragment_parts);
// Re-assemble the fragment
$new_fragment = implode('/', $fragment_parts);
}
// Re-assemble the url
$new_url = $scheme . '://' . $host . $new_fragment;
echo $new_url;
?>
It looks like you are simply looking for a posts' parent. That being the case you need to use 'get_post_ancestors($post->ID)'.
From the wordpress codex...
</head>
<?php
/* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
$class = '';
/* is it a page */
if( is_page() ) {
global $post;
/* Get an array of Ancestors and Parents if they exist */
$parents = get_post_ancestors( $post->ID );
/* Get the top Level page->ID count base 1, array base 0 so -1 */
$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
/* Get the parent and set the $class with the page slug (post_name) */
$parent = get_page( $id );
$class = $parent->post_name;
}
?>
<body <?php body_class( $class ); ?>
This will do what you're asking -
echo implode('/',array_slice(explode('/',get_permalink( $post->ID )),0,-1))
but it's weak.
Only use as solution as simple as this if you can guarantee you won't have any additional stuff at the end of the URL that you need to keep.
There are many ways (explode, strpos and substr, regex). Using regex you can do something like this:
$url = 'http://example.com/apples/dogs/coffee';
$url = preg_replace('#/[^/]+?$#', '', $url);

How to Parse the Interlink Page in php

I Want to Parse Show Time of Some city from Google Page:
Here I Get Movie Names from Page1:
http://www.google.co.in/movies?near=chennai&hl=en&ei=8OIaUr-0EYrFkwX9kICQCA_&date=0
And I Get Show timings from Page2:
http://www.google.co.in/movies?near=chennai&hl=en&ei=8OIaUr-0EYrFkwX9kICQCA_&date=0&tid=8a030c04960c6341
My Php Code:
$htm = file_get_html('http://www.google.co.in/movies?near=chennai&hl=en&ei=8OIaUr-0EYrFkwX9kICQCA_&date=0');
$linker = $htm->find('div h2 a');
$value = $linker[2]->href;
$link = "http://www.google.co.in$value";
$htmls = file_get_html($link);
If I echo "$link"; it Print Same link as Page 2:
$cinemaname = $htmls->find('div[class=name]');
$cinematimes = $htmls->find('div[class=times]');
echo strip_tags($cinemaname[0])."<div>";
echo strip_tags($cinematimes[0])."<div>";
If I echo $cinemaname[0]"; It Printing from Page 1, but I want to Print from Page2.
This issue about link encoded. Your link was return below: &
http://www.google.co.in/movies?near=chennai&hl=en&ei=8OIaUr-0EYrFkwX9kICQCA_&date=0&tid=8a030c04960c6341
You have to decode it with html_entity_decode function
$value = $linker[2]->href;
$link = html_entity_decode("http://www.google.co.in".$value);
$htmls = file_get_html($link);

Categories