I am working on a language switcher, and I use PHP to change the URL from a language to another. I want the language switching button (i.e. link) to change its href attribute when the page loads. Here's my code:
<?php
$actual_link = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if (strpos($actual_link, 'fr') !== false) {
$actual_lang = 'fr';
$new_link = str_replace('/fr/','/en/',$actual_link);
}
else {
$actual_lang = 'en';
$new_link = str_replace('/en/','/fr/',$actual_link);
}
echo "
<div class='top-bar'>
<a class='language-selector' id='language-switch-btn' href='#'>Language</a>
</div>
<script type='text/javascript'>
document.getElementById('language-switch-btn').href = '".$new_link."';
</script>
";
?>
However, my problem is that the JS code concatenates the $new_link to the $actual_link, resulting in the href attribute like this: localhost/website.com/fr/localhost/website.com/en/ when I would want it to be only localhost/website.com/en/
Any idea why it doesn't replace '#' by $newlink ? Thank you
$_SERVER['HTTP_HOST'] doesn't include the protocol, and without the protocol links are relative.
You can prefix the href with // to allow any http protocol (either http or https), but as mentioned in the comment you also don't need JS to do this.
echo "
<div class='top-bar'>
<a class='language-selector'
id='language-switch-btn'
href='//".$new_link."'>Language</a>
</div>
";
Related
I am new to PHP and want to create a link with parameters.
So I used this :
<li>
<!-- $GLOBALS["ROOT_PATH"] is where my index.php file located -->
<a href="<?php echo $GLOBALS["ROOT_PATH"]."/Views/pages/profile.php"; ?>">
Profile
</a>
</li>
but when I click on the page it doesn't send me to the page or do anything. When I look at the URL it's something like file:///C:/bla/bla/bla/Views/pages/profile.php
Edit:
Basically, I want to use this in my header.php but my files are :
index.php
Views/pages/profile.php
and so on.
When I use the relative path for the header the path changes for these pages. How can I solve this?
So I solved it using some tricky way but it works :
function createLink($url,$text,$class){
echo "<li>";
// Gets the current php file name.
$basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4);
if($basename !== "index"){
$url = "../../".$url;
}
echo '<a href="'. $url . '">';
echo '<span class="'.$class.'"></span>';
echo ' '.$text.'';
echo "</a>";
echo "</li>";
}
So it just add the relative path if the file name is not index.php.
I want to fetch the <a> link within the div glance_details. I can't really make it work. Don't worry about including and the url and things, that is all correct.
$redirect = $url;
$html3 = file_get_html($redirect);
foreach($html3->find('div.glance_details') as $element3) {
$html3->find('a',0)->outertext;
}
with
$redirect = $url;
$html3 = file_get_html($redirect);
foreach($html3->find('div.glance_details') as $element3) {
$knaoss = $element3->plaintext;
echo $knaoss;
}
I can fetch the plain text content of the div, but what I want is the anchor (a) that will be within the div.
This is similar to what I receive in $knaoss if I remove the ->plaintext:
<div class="glance_details">
<a href="http://www.example.com/">
<img src="http://www.example.com/img.png">
</a>
"This is a description of the example"
</div>
Though all I want from it is:
http://www.example.com/
I must delete this answer because do not match the OP requirements after he has posted the requested HTML code
The solution was simple. Only had to change:
$redirect = $url;
$html3 = file_get_html($redirect);
foreach($html3->find('div.glance_details') as $element3) {
$knaoss = $element3->plaintext;
}
to
$redirect = $url;
$html3 = file_get_html($redirect);
foreach($html3->find('div.glance_details > a') as $element3) {
$knaoss = $element3->href;
}
to find the href within div.glance_details. Problem was I used words like "url" and "link" instead of href, and could therefor not make it work.
Im using Curl with simple html dom to scrape a website and in order to fix relative links I insert a base tag like this:
foreach($html->find('head') as $f) {
$f->innertext = "<base href='$url'>" . $f->innertext;
}
Where $url is the website Im scraping. The problem is that the links are physically outputted like this:
link
While I need the full url in the link like so:
link
How can I achieve this?
append the url each time you are setting it.
$base_url = "http://www.somewebsite.com/";
foreach($html->find('head') as $f) {
$f->innertext = "<base href='$base_url$url'>" . $f->innertext;
}
Try to get the base URL like this:
<?php
$baseURL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
then prepend $baseURL to your href
I just want to know how can I add a _blank target type to a link if a link is pointing to an external domain (_self for internals). I was doing this by checking the url but it was really hard coded and not reusable for other sites.
Do you have any idea of how to do it properly with PHP ?
$target_type=(strpos($ref, $_SERVER['HTTP_HOST'])>-1
|| strpos($ref,'/')===0? '_self' : '_blank');
if ($ref<>'#' && substr($ref,0,4)<>'http') $ref='http://'.$ref;
$array['href']=$ref;
if (substr($ref,0,1)<>'#') $array['target']= $target_type;
$array['rel']='nofollow';
if (empty($array['text'])) $array['text']=str_replace('http://','',$ref);
This is only working for the main domain, but when using domain.com/friendlyurl/, is not working.
Thanks in advance
NOTE : Links can contain whether http:// protocol or not and they use to be absolute links. Links are added by users in the system
The easiest way is to use parse_url function. For me it should look like this:
<?php
$link = $_GET['link'];
$urlp = parse_url($link);
$target = '_self';
if (isset($urlp['host']) && $urlp['host'] != $_SERVER['HTTP_HOST'])
{
if (preg_replace('#^(www.)(.*)#D','$2',$urlp['host']) != $_SERVER['HTTP_HOST'] && preg_replace('#^(www.)(.*)#D','$2',$_SERVER['HTTP_HOST']) != $urlp['host'])
$target = '_blank';
}
$anchor = 'LINK';
// creating html code
echo $target.'<br>';
echo '' . $link . '';
In this code I use $_GET['link'] variable, but you should use your own link from as a value of $link. You can check this script here: http://kolodziej.in/help/link_target.php?link=http://blog.kolodziej.in/2013/06/i-know-jquery-not-javascript/ (return _blank link), http://kolodziej.in/help/link_target.php?link=http://kolodziej.in/ (return _self link).
Relatively new to php and looking for some help in updating links on a specific page. The page has numerous links eg. href=/link/ and I would like to code the page to identify these links (links that do not already have http or https) and prepend with a url eg. www.domain.com to each. Basically ending up with href=www.domain.com/link/. Any help would be greatly appreciated.
I think you want to parse a list of URLs and prepend "http://" to the ones that don't have it.
<?php
$links = array('http://www.redditmirror.cc/', 'phpexperts.pro', 'https://www.paypal.com/', 'www.example.com');
foreach ($links as &$link)
{
// Prepend "http://" to any link missing the HTTP protocol text.
if (preg_match('|^https*://|', $link) === 0)
{
$link = 'http://' . $link . '/';
}
}
print_r($links);
/* Output:
Array
(
[0] => http://www.redditmirror.cc/
[1] => http://phpexperts.pro/
[2] => https://www.paypal.com/
[3] => http://www.example.com/
)
*/
Maybe it suffices to just change the base URI of the document with the BASE element:
<base href="http://example.com/link/">
With this the new base URI is http://example.com/link/ instead of the URI of the document. That means, every relative URI is resolved from http://example.com/link/ instead of the document’s URI.
You could always use output buffering at the top of your page with a callback that reformats your hrefs to how you'd like them:
function callback($buffer)
{
return (str_replace(' href="/', ' href="http://domain.com/', $buffer));
}
ob_start('callback');
// rest of your page goes here
ob_end_flush();
Because you left out critical details in your first question, here is the second answer.
Doing what #Nev Stokes says may work, but it will also get more than tags. You should never use regular expressions (or, worse, strp_replace) on HTML.
Instead, use the file_get_html() library and do this:
<?php
require 'simplehtmldom/simple_html_dom.php';
ob_start();
?>
<html>
<body>
<a id="id" href="/my_file.txt">My File</a>
<a name="anchor_link" id="boo" href="mydoc2.txt">My Doc 2</a>
PHP Experts
</body>
</html>
<?php
$output = ob_get_clean();
$html = str_get_html($output);
$anchors = $html->find('a');
foreach ($anchors as &$a)
{
if (preg_match('|^https*://|', $a->href) === 0)
{
// Make sure first char is /.
if ($a->href[0] != '/')
{
$a->href = '/' . $a->href;
}
$a->href = 'http://www.domain.com' . $a->href;
}
}
echo $html->save();
Output:
<html>
<body>
<a id="id" href="http://www.domain.com/my_file.txt">My File</a>
<a name="anchor_link" id="boo" href="http://www.domain.com/mydoc2.txt">My Doc 2</a>
PHP Experts
</body>
</html>