3

Basically, I'm using gethostbyname() to get the IP address of the specified URL, using parse_url() to determine the specific domain. However, this doesn't work if http:// is not in the URL (unless I'm missing an option)

So how can I check if http:// is in the URL, and if not, add it appropriately?

Or if have a better alternative, I'd like to hear it. Thanks.

Rob
  • 7,980
  • 30
  • 75
  • 115

4 Answers4

7
<?php
  $url = [some url here];
  if(substr($url, 0, 7) != 'http://') {
     $url = 'http://' . $url;
  }

?>
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
1

Hmm, strictly speaking, you need to consider https as well, and maybe even ftp and mailto depending on what you are doing. You might want to check for a ':' first, without one you DEFINITELY don't have a protocol, and could skip the rest, with one you might have a protocol, or maybe a port specification.

  <?php 
  $url = [some url here]; 
  if(substr($url, 0, 7) != 'http://') { 
      if(substr($url, 0, 8) != 'https://') { 
         $url = 'http://' . $url; 
      } 
  } 

?>

etc

Roger Willcocks
  • 1,649
  • 13
  • 27
1

Simple solution:

if(!preg_match('/http[s]?:\/\//', $url, $matches)) $url = 'http://'.$url;
cypher
  • 6,822
  • 4
  • 31
  • 48
-4

if (strpos("http://", $url) === "true"){ action };

Nik
  • 2,424
  • 3
  • 18
  • 16
  • 1
    This comparison will not work. strpos returns an integer on success, and boolean `false` if the string is not found. It will not ever return boolean `true` and certainly not string `'true'`. `if (strpos("http://", $url) !== false)` would test if it was found in the whole string, or to see if it's at the start of the string, `if (strpos("http://", $url) === 0)` – JAL Jun 20 '10 at 23:57