38

Hello I have a very simple code

<a href="'.$aProfileInfo['Website'].'" target="_self">
    <div class="callButton">Website</div>
</a>

The problem is that if the user does not enter http:// the link will then point to my website and not to the external website as it should.

How do I check in PHP if the user has not entered http:// and automatically add it when it is not there?

Akhil Jain
  • 13,872
  • 15
  • 57
  • 93
DiegoP.
  • 45,177
  • 34
  • 89
  • 107
  • 2
    Also, _please_ make sure that you are escaping user input before inserting it into html. See [htmlspecialchars()](http://php.net/manual/en/function.htmlspecialchars.php). – Wilbur Vandrsmith Jun 05 '11 at 01:23
  • You can simplify David's answer to work on one line (so you can put it inline with your HTML). See: http://stackoverflow.com/a/24482058/1101095 – Nate Jun 30 '14 at 02:00
  • @Nate actually, you can simplify it even further than that. Also the regular expression way can be a one-liner as well. See: http://stackoverflow.com/a/31549463/1572938 – Evan Kennedy Jul 21 '15 at 21:22
  • This might be a duplicate of http://stackoverflow.com/questions/2762061/how-to-add-http-if-its-not-exists-in-the-url – Adam May 16 '16 at 12:13

10 Answers10

54

I think you'd better use the built in function parse_url() which returns an associative array with its components

something like this will work for you:

 if  ( $ret = parse_url($url) ) {

      if ( !isset($ret["scheme"]) )
       {
       $url = "http://{$url}";
       }
}
Akhil Jain
  • 13,872
  • 15
  • 57
  • 93
David
  • 541
  • 1
  • 3
  • 2
33

I personally use this, which is partially taken from the php docs

$scheme = parse_url($link, PHP_URL_SCHEME);
if (empty($scheme))
    $link = 'https://' . ltrim($link, '/');
Bram Hammer
  • 363
  • 4
  • 21
Satbir Kira
  • 792
  • 6
  • 21
19

A simple solution which may not work in all cases (i.e. 'https://'):

if (strpos($aProfileInfo['Website'],'http://') === false){
    $aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}
Christopher Armstrong
  • 7,907
  • 2
  • 26
  • 28
10

There are two ways of tackling this problem: url parsing and regular expressions.

Some will say url parsing is right, but regular expressions work just as well in this case. I like being able to have simple one-liners for things like this especially because this would be a common occurrence in template files where you may need a one-liner inside an echo statement to maintain readability.

Regular Expressions

We can do this in a single function call with preg_replace.

preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website'])

This uses a negative lookahead at the beginning of the string that looks for http:// or https://. If either are found, the replace doesn't happen. If they aren't found, it replaces the beginning of the string (0 characters) with http:// essentially prepending this to the string without modifying it.

In context:

<a href="'. preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website']).'" target="_self">
    <div class="callButton">Website</div>
</a>

URL Parsing

(parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']

What this does is find out if a scheme is present on the link throught parse_url($aProfileInfo['Website'], PHP_URL_SCHEME). Then using a ternary operator, it will either output '' if there was one found or 'http://' if one wasn't found. Then it appends the link onto that.

In context:

<a href="'.((parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']).'" target="_self">
    <div class="callButton">Website</div>
</a>
Evan Kennedy
  • 3,975
  • 1
  • 25
  • 31
  • 2
    Your regex is smart that it preserves `https://` however it doesn't work with relative urls such as `//www.example.com`. It also appends `http://` onto `ftp://` or other protocols. Try this instead: `preg_replace('/^\/\/|^(?!https?:)(?!ftps?:)/', 'http://', $src)` (note: you can remove the check for ftp if you dont need it) – dhaupin May 13 '16 at 16:05
3

You could use strpos:

// Trim trailing whitespace
$aProfileInfo['Website'] = trim($aProfileInfo['Website']);

// Test if the string begins with "http://"
if (strpos($aProfileInfo['Website'], 'http://') !== 0) {
  $aProfileInfo['Website'] = 'http://' . $aProfileInfo['Website'];
}
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
1

You also may take into account that "http(s)" must be at the beginning of the url:

if (preg_match('/^https?:\/\//', $aProfileInfo['Website']) === 0) {
    $aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}
NDY
  • 3,527
  • 4
  • 48
  • 63
ggonzal
  • 129
  • 1
  • 3
1

You can use this function as a general if nothing from the array is found in the string append something to it.

function httpify($link, $append = 'http://', $allowed = array('http://', 'https://')){

  $found = false;
  foreach($allowed as $protocol)
    if(strpos($link, $protocol) !== 0)
      $found = true;

  if($found)
    return $link;
  return $append.$link;
}
Hailwood
  • 89,623
  • 107
  • 270
  • 423
0

Here is another example with string subtraction:

$changeLink = $myRow->site_url;
  if(substr($changeLink, 0, 7) != 'http://') {
     $changeLink = 'http://' . $changeLink;  
}

// ....

echo "<a href=\"" . $changeLink . "\" target=\"_blank\"></a>";
Porta Shqipe
  • 766
  • 7
  • 8
0

I believe David's answer is the proper way to do this, but it can be simplified like this:

parse_url($aProfileInfo['Website'], PHP_URL_SCHEME)==''?'http://'.$aProfileInfo['Website']:$aProfileInfo['Website']
Community
  • 1
  • 1
Nate
  • 26,164
  • 34
  • 130
  • 214
0

Something like this?

if (!strpos($aProfileInfo['Website'], 'http://')) {
    $aProfileInfo['Website'] = 'http://' . $aProfileInfo['Website'];
}
gpresland
  • 1,690
  • 2
  • 20
  • 31