3

i want something like this

  1. the user enter a website link

  2. i need check the link if the link doesn't start with 'http://' I want to append 'http://' to the link .

how can I do that in PHP ?

Waseem
  • 11,741
  • 15
  • 41
  • 45

4 Answers4

11
if (stripos($url, 'http://') !== 0) {
   $url = 'http://' . $url;
}
Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
  • 1
    Your answer is correct, but I can't stand it when people put the two operands of the comparison operators in that order. – Lucas Oman Nov 07 '08 at 15:28
  • I'm with Lucas on this. My reasoning is that it doesn't make sense if you read it as an english sentence. "if zero does not equal the outcome of this function..." – Lasar Nov 07 '08 at 15:42
  • 3
    It's evidently less readable. But there is a rationale for it in C-derived languages where you can accidentally write ‘if (a=0)’. ‘if (0=a)’ will get caught quickly. Though personally I don't use this style, it is a matter of taste and coding standards. – bobince Nov 07 '08 at 17:04
  • It is personal taste. I always use this notation and I find it more readable. – andy.gurin Nov 08 '08 at 20:50
  • In mathematics, you always put the variable on the left and the quantity on the right. As a habit formed from that, I always follow Lucas's order. – Karan Nov 08 '08 at 20:55
  • Just FYI this order is usually regarded as an anti-pattern - commonly referred to as "Yoda Conditional". – Iain Collins Apr 29 '12 at 02:18
7

I'll recommend a slight improvement over tom's

if (0 !== stripos($url, 'http://') && 0 !== stripos($url, 'https://')) {
   $url = 'http://' . $url;
}

However, this will mess up links that use other protocols (ftp:// svn:// gopher:// etc)

Tom Ritter
  • 99,986
  • 30
  • 138
  • 174
3
if (!preg_match("/^http:\/{2}/",$url)){
    $url = 'http://' . $url;
}
Chris Kloberdanz
  • 4,436
  • 4
  • 30
  • 31
2

I would check for the some letters followed by a colon. According to the URI specifications a colon is used to separate the "schema" (http, ftp etc.) from the "schema specific part". This way if somebody enters (for example) mailto links these are handled correctly.

reefnet_alex
  • 9,703
  • 5
  • 33
  • 32