0

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

themazz
  • 1,107
  • 3
  • 10
  • 29

1 Answers1

0

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 '<a href="' . $link . '" target="' . $target . '">' . $link . '</a>';

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).

Kacper Kołodziej
  • 698
  • 1
  • 9
  • 23
  • if $_SERVER['HTTP_HOST'] is www.foo.com, then "foo.com" will be seen as _blank link. – 蒋艾伦 Jun 07 '13 at 09:11
  • I have done some corrections in code, I think it should work properly now. – Kacper Kołodziej Jun 07 '13 at 09:27
  • AaronJiang: we can check if there is a protocol set in url at the beginning. When you don't have protocol and you don't know if internal links begins with / or not, you cannot decide surely what type of link it is. – Kacper Kołodziej Jun 07 '13 at 09:29
  • Yes, in this case, you may have to filter links without "http://", which cannot be parsed using parse_url. :) – 蒋艾伦 Jun 07 '13 at 14:27
  • But when you haven't any protocol, you don't know if the path: youdomain.com/index.html is /yourdomain.com/index.html (yourdomain.com is a directory) or http://yourdomain.com/index.html. – Kacper Kołodziej Jun 08 '13 at 06:20