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.

1

4 Answers 4

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

?>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

Simple solution:

if(!preg_match('/http[s]?:\/\//', $url, $matches)) $url = 'http://'.$url;

Comments

-4

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

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.